String Literals and Escape Sequences
How fixed values are written in code, how string literals work, and how escape sequences put quotation marks, backslashes, and line breaks inside text.
A literal is the code representation of a fixed value, such as 42, 3.5, true, or "Hello". A string literal is a sequence of characters enclosed in double quotes. Because the double quote marks the beginning and end of a string literal, some characters cannot simply be typed inside one. Escape sequences solve this: special two-character combinations that start with a backslash. Three are used here: \" for a double quote, \\ for a backslash, and \n for a newline.
1Literals: Fixed Values in Code
Most values in a program are computed, read from data, or stored in variables. A literal is different: it is a value written directly into the code, and it never changes. In int laps = 12;, the 12 is an int literal. In String greeting = "Welcome";, "Welcome" is a String literal.
The way a literal is written determines its type. Whole numbers without a decimal point are int literals; numbers with a decimal point are double literals; true and false are the two boolean literals; and anything in double quotes is a String literal. The special literal null indicates that a reference variable is not associated with any object.
Recognizing literal types matters because the type determines what operators do. 10 + 5 is 15, but "10" + 5 is "105", because the first operand is text.
String literal, even when they look like a number.| Literal | Type | Notes |
|---|---|---|
7 | int | Whole number, no decimal point |
7.0 | double | Decimal point makes it a real number |
false | boolean | One of the two boolean literals |
"7" | String | Characters in double quotes |
"" | String | The empty string: zero characters |
null | Reference (no object) | Means a reference variable refers to nothing |
Text That Looks Like a Number
Predict the output.
System.out.println(10 + 5);
System.out.println("10" + 5);
System.out.println("10" + "5");
System.out.println("" + 10 + 5);
15
105
105
105
- 1Line 1. Two
intliterals add to 15. - 2Lines 2 and 3.
"10"is aStringliteral, so+joins: "105". - 3Line 4. The empty string literal makes the first
+a join, and the rest follow: "105".
"" is a quick way to start a join.2String Literals
A string literal is a sequence of characters enclosed in double quotes. It can contain letters, digits, spaces, and punctuation: "Room 214, 2nd floor!". The quotes themselves are not part of the string; they only mark where it begins and ends. When the string is printed, the quotes do not appear.
A string literal must begin and end on the same line of code. If a string is long, it can be split into pieces joined with +. The shortest string literal is "", the empty string, which contains zero characters. The empty string is a real String value, different from null, which means there is no string at all.
Inside a literal, spaces count. "Hi" and "Hi " are different strings, with lengths 2 and 3. This is why spacing in output depends entirely on what you type inside the quotes.
Long text is often built from several literals joined with +, written across multiple lines of code so that no single line becomes too wide to read:
String note = "Practice starts at 4:00. "
+ "Bring water, cleats, "
+ "and your signed form.";
System.out.println(note);
Practice starts at 4:00. Bring water, cleats, and your signed form.
Each piece is a complete literal with its own opening and closing quotes, and the spaces that separate words sit inside the literals. The resulting string is a single line of text; splitting the code across lines does not add any line breaks to the string itself.
3Escape Sequences
Suppose a program must print a line that contains quotation marks. Typing a double quote inside a string literal would end the literal, confusing the compiler. Escape sequences are special sequences of characters that can be included in a string. They start with a backslash \ and have a special meaning in Java. The backslash is called the escape character: it tells the compiler that the next character should be treated differently.
\"produces a double quote inside the string, without ending the literal.\\produces a single backslash. Because a lone backslash would start an escape sequence, a backslash you want to display must be doubled.\nproduces a newline character, which moves the output to the start of the next line.
Using a backslash followed by a character that does not form a valid escape sequence causes a compile-time error. When you need a backslash in output, such as in a file path, always write \\.
Escape sequences exist because some characters play two roles. The double quote is both a character someone might want to print and the symbol that marks where a literal ends. The backslash is both a printable character and the signal that an escape sequence begins. The newline is a character with no visible symbol at all, so there is no way to type it inside a one-line literal. Escaping gives each of these a second, unambiguous spelling, so the compiler can always tell which role is intended.
When reading code, translate each escape sequence before predicting output: replace every \" with a quote, every \\ with a backslash, and every \n with a line break. Doing this translation first, and only then thinking about print versus println, keeps the two sources of confusion separate.
\n, the slash in "one / two" stands for the line break.)| Escape sequence | Produces | Example literal | Displays |
|---|---|---|---|
\" | A double quote character | "She said \"yes\"" | She said "yes" |
\\ | A single backslash | "a\\b" | a\b |
\n | A newline (line break) | "top\nbottom" | top, then bottom on the next line |
Printing a Quotation
Print this exact line: The coach said "Run it again."
System.out.println("The coach said "Run it again."");
- 1Why it fails. The second
"ends the string literal early, leavingRun it again.outside any string, which is not valid code. - 2Escape the inner quotes.
\"tells Java "this is a quote character, not the end of the literal."FixedSystem.out.println("The coach said \"Run it again.\"");OutputThe coach said "Run it again."
\" for each inner quotation mark prints the quotation correctly.Printing a File Path
Print the folder path C:\notes\week2 exactly.
System.out.println("C:\\notes\\week2");
C:\notes\week2
- 1One backslash needs two. Because a backslash starts an escape sequence, a literal backslash must be written
\\. - 2What would go wrong. Writing
"C:\notes\week2"would turn\ninto a newline, and\wis not a legal escape sequence at all, so the code would not compile.
"C:\\notes\\week2" prints C:\notes\week2. Every backslash you want displayed must be doubled.In a string literal, \ is never displayed by itself. "C:\new" contains a newline, not the letters backslash-n, and many other combinations do not compile. To display one backslash, type two: "C:\\new".
4Newlines Inside Strings
The \n escape sequence lets one string span several lines of output. Every \n moves the cursor to the beginning of a new line, and two in a row produce a blank line. This combines naturally with print and println: System.out.println("A\nB") prints A and B on separate lines and then ends the line after B, while System.out.print("A\nB") prints the same two lines but leaves the cursor right after B.
Using \n is a convenient way to print a short block such as a menu in a single statement. For longer output, separate println statements are usually easier to read and change, because each line of code matches one line of output.
\n inside a string starts a new line of output, so one statement can print several lines.Several Lines From One Statement
Predict the output.
System.out.print("Menu:\n1. Start\n2. Quit\n");
System.out.println("Choose an option");
Menu:
1. Start
2. Quit
Choose an option
- 1Each
\nends a line. The first statement prints three lines, and its final\nleaves the cursor at the start of a fourth line. - 2
printadds no extra line break. Because the string already ends with\n, usingprinthere behaves likeprintlnwould without the final\n. - 3The last statement prints on the fresh line.
Menu:, 1. Start, 2. Quit, and Choose an option.A Shipping Label in One Statement
Print this three-line label with a single println, including the quotation marks around the nickname:
To: Lin "Ace" ParkUnit 5\BFragile
System.out.println("To: Lin \"Ace\" Park\nUnit 5\\B\nFragile");
To: Lin "Ace" Park
Unit 5\B
Fragile
- 1Line breaks. Two
\nsequences split the text into three lines;printlnends the last line. - 2Quotes. Each quotation mark around Ace is written
\"so it does not end the literal. - 3Backslash. The backslash in the unit number is written
\\. - 4Check by translating. Replace each escape sequence with the character it produces, then read the result line by line; it matches the label exactly.
System.out.println("Done\n"); prints "Done," then the newline from \n, then another line break from println, leaving a blank line. When output contains unexpected blank lines, look for a \n at the end of a string printed with println.
5Counting the Characters in a String
What a string contains is not always what its literal looks like. Each escape sequence takes two characters to type but becomes one character in the string. The literal "Hi\n\"Jo\"" takes 12 characters to type (counting its outer quotes), but the string it creates has 7 characters: H, i, a newline, a quote, J, o, and a quote. The length() method reports the number of characters actually in the string.
This distinction matters whenever a program measures or slices text. Positions in a string count actual characters, starting from 0, so a newline or escaped quote occupies exactly one position.
String contains differs from how its literal is typed. Escape sequences occupy two characters in the code but become a single character in the string.Counting Characters in a Literal
How many characters does each string contain? Check with length().
System.out.println("Hi\n\"Jo\"".length());
System.out.println("".length());
System.out.println(" ".length());
System.out.println("a\\b".length());
7
0
1
3
- 1
"Hi\n\"Jo\"". H, i, newline, quote, J, o, quote: 7 characters, as in Figure 4. - 2
"". The empty string contains no characters: length 0. - 3
" ". A space is a character: length 1. - 4
"a\\b". a, one backslash, b: length 3.
6Common Literal Mistakes
Most string-literal errors are caught by the compiler, which makes them quick to fix once you know what to look for. An unescaped quote ends the literal too early; a missing closing quote leaves the literal unfinished; a backslash followed by an unexpected character is an illegal escape; and a literal cannot be broken across two lines of code. Each error message points to the line, and the fix is usually a single character.
| Mistake | Example | Result | Fix |
|---|---|---|---|
| Unescaped inner quote | "He said "hi"" | Compile error | Use \" |
| Single backslash | "a\b" | Compile error or wrong character | Use \\ |
| Missing closing quote | "Hello); | Compile error | Close the literal |
| Line break typed inside quotes | A literal split across two lines of code | Compile error | Use \n or join two literals with + |
An Escape Sequence That Does Not Exist
A student tries to print the cheering emoticon Yay \o/. Explain the error and fix it.
System.out.println("Yay \o/");
- 1The problem. Inside a string, a backslash always starts an escape sequence.
\ois not an escape sequence Java recognizes, so the compiler reports an error instead of printing a backslash. - 2The fix. Double the backslash.
Fixed
System.out.println("Yay \\o/");OutputYay \o/
"Yay \\o/" prints Yay \o/. A single backslash is never printed as itself."" is a String object with length 0. null means a variable refers to no object at all. Calling length() on "" returns 0; calling it on null throws a NullPointerException.
"5" + "3" is "53", not 8, and "5" * 3 does not compile, because multiplication is not defined for strings. If a value will be used in arithmetic, write it without quotes.
Four Habits for String Literals
1. Quotes Mark Boundaries
Anything between double quotes is text; the quotes themselves never print.
2. Escape the Specials
Inner quotes need \", backslashes need \\, line breaks use \n.
3. Count Real Characters
Each escape sequence is one character in the string.
4. Empty Is Not Null
"" is a string with no characters; null is no string at all.
A literal is the code representation of a fixed value, and its form determines its type. A string literal is a sequence of characters enclosed in double quotes. Escape sequences are special sequences of characters that can be included in a string; they start with a backslash and have a special meaning in Java. The escape sequences used here are double quote \", backslash \\, and newline \n. Each one is a single character in the resulting string.