Skip to lesson

Quoted fields and commas inside values

A value can contain a comma itself: a name like Rao, Asha, an address or a book title. CSV handles this by putting such a value inside double quotes, and a program that only does split(",") cuts it in the wrong place.

Why split on comma breaks

A quoted field is a CSV value wrapped in double quotes, so a comma, a quote or a line break inside it belongs to the value and does not end the field.

split(",") cuts at every comma, including commas that belong inside a value. The line 101,"Rao, Asha",87 has 3 fields, but split returns 4 pieces: 101, "Rao, Asha" and 87.

The CSV line 3,"Rao, Asha",82. Splitting on every comma cuts the quoted name in two and gives four wrong pieces. A quote-aware parser keeps the comma inside the quotes and gives the three correct fields: 3, Rao, Asha and 82.

Example 1 · split cuts inside a quoted name

SplitBreaksDemo.javaJava
public class SplitBreaksDemo {    public static void main(String[] args) {        String line = "101,\"Rao, Asha\",87";        System.out.println("Line: " + line);
        String[] f = line.split(",", -1);        System.out.println("Pieces: " + f.length);        for (String p : f) {            System.out.println("[" + p + "]");        }
        try {            int marks = Integer.parseInt(f[2].trim());            System.out.println("Marks: " + marks);        } catch (NumberFormatException e) {            System.out.println("Marks field: " + e.getMessage());        }    }}
Output
Line: 101,"Rao, Asha",87
Pieces: 4
[101]
["Rao]
[ Asha"]
[87]
Marks field: For input string: "Asha""

What this code does

  • The value Rao, Asha contains a comma, so split breaks it into "Rao and Asha". The row seems to have 4 fields instead of 3.
  • Index 2 now holds part of the name, so parseInt fails with For input string: "Asha"". Other files may load wrong values with no error at all.

The damage is quiet. The field count is wrong, the quotes stay in the name, and the marks end up at the wrong index. Some rows fail with an exception, others load with the wrong values. Excel and Google Sheets add these quotes on their own whenever a cell contains a comma. So any CSV that came from a spreadsheet can have them, even if you never typed a quote.

Predict the output

Predict what split gives

split cuts at every comma, even inside quotes.

Round 1 of 2

How many pieces does the line give?

String line = "3,\"Rao, Asha\",82";
System.out.println(line.split(",").length);

Quoting rules and doubled quotes

The common CSV rules (written down in RFC 4180) are short. A field that contains a comma, a double quote or a line break is wrapped in double quotes: "Rao, Asha".

Example 2 · Turning one quoted field back into its value

UnquoteDemo.javaJava
public class UnquoteDemo {    static String unquote(String field) {        if (field.length() >= 2 && field.startsWith("\"") && field.endsWith("\"")) {            String inner = field.substring(1, field.length() - 1);            return inner.replace("\"\"", "\"");        }        return field;    }
    public static void main(String[] args) {        String[] stored = {"Asha", "\"Rao, Asha\"", "\"5\"\" screen\"", "\"\""};        for (String s : stored) {            System.out.println(s + "  ->  [" + unquote(s) + "]");        }    }}
Output
Asha  ->  [Asha]
"Rao, Asha"  ->  [Rao, Asha]
"5"" screen"  ->  [5" screen]
""  ->  []

What this code does

  • Each line shows a field as stored in the file, then its real value in square brackets. The outer quotes go, and each "" inside becomes one ".
  • unquote only works on one field that is already cut out. It cannot find where the fields start and end, which is why the next example reads the line one character at a time.

A double quote inside a quoted field is written twice: the value 5" screen is stored as "5"" screen". This is called a doubled quote. When you read the field, "" turns back into one ". The quotes are not part of the value. "Asha" and Asha mean the same text, and "" is an empty field. Fields without special characters usually have no quotes at all.

  • Asha → Asha
  • "Rao, Asha" → Rao, Asha
  • "5"" screen" → 5" screen
  • "" → an empty field

A small character-by-character parser

A parser reads text and builds structured data from it. To respect quotes, it must look at one character at a time and remember one fact: is it inside quotes right now?

Example 3 · The character-by-character parser

CsvParserDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class CsvParserDemo {    static List<String> parseLine(String line) {        List<String> fields = new ArrayList<>();        StringBuilder field = new StringBuilder();        boolean inQuotes = false;        for (int i = 0; i < line.length(); i++) {            char c = line.charAt(i);            if (inQuotes) {                if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') {                    field.append('"');          // "" inside quotes is one quote                    i++;                } else if (c == '"') {                    inQuotes = false;                } else {                    field.append(c);                }            } else if (c == ',') {                fields.add(field.toString());                field.setLength(0);            } else if (c == '"' && field.length() == 0) {                inQuotes = true;                // opening quote at the start of a field            } else {                field.append(c);            }        }        if (inQuotes) {            throw new IllegalArgumentException("Unclosed quote in: " + line);        }        fields.add(field.toString());           // the last field has no comma after it        return fields;    }
    public static void main(String[] args) {        String[] lines = {            "101,\"Rao, Asha\",87",            "B-12,\"The \"\"Wings of Fire\"\" copy\",2",            "103,,92"        };        for (String line : lines) {            List<String> f = parseLine(line);            System.out.println(f.size() + " fields: " + String.join(" | ", f));        }        try {            parseLine("104,\"Dev Sharma,77");        } catch (IllegalArgumentException e) {            System.out.println(e.getMessage());        }    }}
Output
3 fields: 101 | Rao, Asha | 87
3 fields: B-12 | The "Wings of Fire" copy | 2
3 fields: 103 |  | 92
Unclosed quote in: 104,"Dev Sharma,77

What this code does

  • inQuotes is the one fact the parser remembers. While it is true, a comma is added to the value; while it is false, a comma ends the field.
  • The doubled quotes around Wings of Fire become single quotes in the value, the empty middle field of 103,,92 stays as an empty string, and a line that ends inside quotes is rejected.

Outside quotes, a comma ends the field and a quote at the start of a field opens quotes. Inside quotes, a comma is plain text, "" adds one quote, and a single " closes the quotes. At the end of the line, the last field is added. If the line ends while still inside quotes, the line is broken. The parser returns a List<String> of clean values. Your fromCsv method then works on that list exactly as it did on the result of split.

This parser reads one line at a time, so it cannot handle a quoted value that contains a line break: it reports an unclosed quote. Real projects use a library such as Apache Commons CSV or OpenCSV, which handle that case.

Testing the parser with tricky lines

A parser has many small paths, and a bug in one only shows on certain lines. Test it with a table of cases: each input line next to the exact fields you expect, and a check that prints PASS or FAIL.

Example 4 · A test table of tricky lines

CsvParserTest.javaJava
import java.util.ArrayList;import java.util.List;
public class CsvParserTest {    static List<String> parseLine(String line) {        List<String> fields = new ArrayList<>();        StringBuilder field = new StringBuilder();        boolean inQuotes = false;        for (int i = 0; i < line.length(); i++) {            char c = line.charAt(i);            if (inQuotes) {                if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') {                    field.append('"');          // "" inside quotes is one quote                    i++;                } else if (c == '"') {                    inQuotes = false;                } else {                    field.append(c);                }            } else if (c == ',') {                fields.add(field.toString());                field.setLength(0);            } else if (c == '"' && field.length() == 0) {                inQuotes = true;                // opening quote at the start of a field            } else {                field.append(c);            }        }        if (inQuotes) {            throw new IllegalArgumentException("Unclosed quote in: " + line);        }        fields.add(field.toString());           // the last field has no comma after it        return fields;    }
    static int passed = 0;    static int failed = 0;
    static void check(String line, List<String> expected) {        List<String> actual = parseLine(line);        if (actual.equals(expected)) {            passed++;            System.out.println("PASS " + line);        } else {            failed++;            System.out.println("FAIL " + line + " expected " + expected + " but got " + actual);        }    }
    public static void main(String[] args) {        check("a,b,c", List.of("a", "b", "c"));        check("", List.of(""));        check(",,", List.of("", "", ""));        check("\"Rao, Asha\",87", List.of("Rao, Asha", "87"));        check("\"\",x", List.of("", "x"));        check("\"say \"\"hi\"\"\"", List.of("say \"hi\""));        check("5\" screen,TV", List.of("5\" screen", "TV"));        check("a,b,", List.of("a", "b", ""));        try {            parseLine("\"open,never closed");            failed++;            System.out.println("FAIL unclosed quote was accepted");        } catch (IllegalArgumentException e) {            passed++;            System.out.println("PASS unclosed quote rejected");        }        System.out.println(passed + " passed, " + failed + " failed");    }}
Output
PASS a,b,c
PASS
PASS ,,
PASS "Rao, Asha",87
PASS "",x
PASS "say ""hi"""
PASS 5" screen,TV
PASS a,b,
PASS unclosed quote rejected
9 passed, 0 failed

What this code does

  • Each check call is one test case: an input line and the list of fields expected. List.equals compares the two lists item by item.
  • All 9 pass, so the parser handles every rule from this lesson.

Pick the edge cases, the unusual inputs where bugs hide: an empty line, empty fields, a comma inside quotes, a doubled quote, a quoted empty field, a quote in the middle of a plain field and an unclosed quote.

Run the table after every change to the parser. When a real file breaks your import, add its line to the table first, then fix the parser until every case passes.

Example 5 · Using the parser in a real import

QuotedImportDemo.javaJava
import java.util.ArrayList;import java.util.List;
record Student(int roll, String name, String city, int marks) {    static Student fromFields(List<String> f) {        if (f.size() != 4) {            throw new IllegalArgumentException("Expected 4 fields but got " + f.size());        }        return new Student(Integer.parseInt(f.get(0).trim()), f.get(1).trim(),                f.get(2).trim(), Integer.parseInt(f.get(3).trim()));    }}
public class QuotedImportDemo {    static List<String> parseLine(String line) {        List<String> fields = new ArrayList<>();        StringBuilder field = new StringBuilder();        boolean inQuotes = false;        for (int i = 0; i < line.length(); i++) {            char c = line.charAt(i);            if (inQuotes) {                if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') {                    field.append('"');          // "" inside quotes is one quote                    i++;                } else if (c == '"') {                    inQuotes = false;                } else {                    field.append(c);                }            } else if (c == ',') {                fields.add(field.toString());                field.setLength(0);            } else if (c == '"' && field.length() == 0) {                inQuotes = true;                // opening quote at the start of a field            } else {                field.append(c);            }        }        if (inQuotes) {            throw new IllegalArgumentException("Unclosed quote in: " + line);        }        fields.add(field.toString());           // the last field has no comma after it        return fields;    }
    public static void main(String[] args) {        List<String> file = List.of(                "roll,name,city,marks",                "101,\"Rao, Asha\",\"Bengaluru, Karnataka\",87",                "102,Bhavesh Patel,Surat,64",                "103,\"Iyer, Chitra\",Chennai,92");        int total = 0;        for (String line : file.subList(1, file.size())) {            Student s = Student.fromFields(parseLine(line));            System.out.println(s.name() + " | " + s.city() + " | " + s.marks());            total += s.marks();        }        System.out.println("Total marks: " + total);    }}
Output
Rao, Asha | Bengaluru, Karnataka | 87
Bhavesh Patel | Surat | 64
Iyer, Chitra | Chennai | 92
Total marks: 243

What this code does

  • fromFields takes the clean List<String> from the parser instead of a raw line. The checks and conversions are the same as before; only the cutting step changed.
  • Names and cities with commas now load correctly. split(",") would have given 5 or 6 pieces for the first and third rows.

Next step

Check your understanding

12 quick questions