AP Computer Science A · Study guide

String Literals and Escape Sequences

AP® Computer Science A · Using Objects and Methods

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.

Big Picture

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.

Figure 1. The form of a literal determines its type. Characters inside double quotes always form a String literal, even when they look like a number.
LiteralTypeNotes
7intWhole number, no decimal point
7.0doubleDecimal point makes it a real number
falsebooleanOne of the two boolean literals
"7"StringCharacters in double quotes
""StringThe empty string: zero characters
nullReference (no object)Means a reference variable refers to nothing
Worked Example 1 Literal types

Text That Looks Like a Number

Predict the output.

Code
System.out.println(10 + 5);
System.out.println("10" + 5);
System.out.println("10" + "5");
System.out.println("" + 10 + 5);
Output
15
105
105
105
  1. 1Line 1. Two int literals add to 15.
  2. 2Lines 2 and 3. "10" is a String literal, so + joins: "105".
  3. 3Line 4. The empty string literal makes the first + a join, and the rest follow: "105".
Result: Only the first line adds. Quotation marks turn digits into text, and the empty string "" 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:

Joining literals across lines
String note = "Practice starts at 4:00. "
    + "Bring water, cleats, "
    + "and your signed form.";
System.out.println(note);
Output
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.
  • \n produces 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.

Figure 2. An escape sequence starts with a backslash and gives the next character a special meaning. (For \n, the slash in "one / two" stands for the line break.)
Escape sequenceProducesExample literalDisplays
\"A double quote character"She said \"yes\""She said "yes"
\\A single backslash"a\\b"a\b
\nA newline (line break)"top\nbottom"top, then bottom on the next line
Worked Example 2 Quotes inside strings

Printing a Quotation

Print this exact line: The coach said "Run it again."

First attempt (does not compile)
System.out.println("The coach said "Run it again."");
  1. 1Why it fails. The second " ends the string literal early, leaving Run it again. outside any string, which is not valid code.
  2. 2Escape the inner quotes. \" tells Java "this is a quote character, not the end of the literal."
    Fixed
    System.out.println("The coach said \"Run it again.\"");
    Output
    The coach said "Run it again."
Result: Writing \" for each inner quotation mark prints the quotation correctly.
Worked Example 3 Backslashes

Printing a File Path

Print the folder path C:\notes\week2 exactly.

Code
System.out.println("C:\\notes\\week2");
Output
C:\notes\week2
  1. 1One backslash needs two. Because a backslash starts an escape sequence, a literal backslash must be written \\.
  2. 2What would go wrong. Writing "C:\notes\week2" would turn \n into a newline, and \w is not a legal escape sequence at all, so the code would not compile.
Result: "C:\\notes\\week2" prints C:\notes\week2. Every backslash you want displayed must be doubled.
Common Mistake 1 · Writing a Single Backslash

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.

Figure 3. Every \n inside a string starts a new line of output, so one statement can print several lines.
Worked Example 4 Newlines

Several Lines From One Statement

Predict the output.

Code
System.out.print("Menu:\n1. Start\n2. Quit\n");
System.out.println("Choose an option");
Output
Menu:
1. Start
2. Quit
Choose an option
  1. 1Each \n ends a line. The first statement prints three lines, and its final \n leaves the cursor at the start of a fourth line.
  2. 2print adds no extra line break. Because the string already ends with \n, using print here behaves like println would without the final \n.
  3. 3The last statement prints on the fresh line.
Result: The output is four lines: Menu:, 1. Start, 2. Quit, and Choose an option.
Worked Example 5 Putting it together

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" Park
Unit 5\B
Fragile

Code
System.out.println("To: Lin \"Ace\" Park\nUnit 5\\B\nFragile");
Output
To: Lin "Ace" Park
Unit 5\B
Fragile
  1. 1Line breaks. Two \n sequences split the text into three lines; println ends the last line.
  2. 2Quotes. Each quotation mark around Ace is written \" so it does not end the literal.
  3. 3Backslash. The backslash in the unit number is written \\.
  4. 4Check by translating. Replace each escape sequence with the character it produces, then read the result line by line; it matches the label exactly.
Result: One literal with five escape sequences produces the whole label. Translating escapes first makes output like this easy to predict and to write.
Common Mistake 2 · Doubling Line Breaks by Accident

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.

Figure 4. What a 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.
Worked Example 6 Length

Counting Characters in a Literal

How many characters does each string contain? Check with length().

Code
System.out.println("Hi\n\"Jo\"".length());
System.out.println("".length());
System.out.println(" ".length());
System.out.println("a\\b".length());
Output
7
0
1
3
  1. 1"Hi\n\"Jo\"". H, i, newline, quote, J, o, quote: 7 characters, as in Figure 4.
  2. 2"". The empty string contains no characters: length 0.
  3. 3" ". A space is a character: length 1.
  4. 4"a\\b". a, one backslash, b: length 3.
Result: The lengths are 7, 0, 1, and 3. Each escape sequence counts as one character.

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.

MistakeExampleResultFix
Unescaped inner quote"He said "hi""Compile errorUse \"
Single backslash"a\b"Compile error or wrong characterUse \\
Missing closing quote"Hello);Compile errorClose the literal
Line break typed inside quotesA literal split across two lines of codeCompile errorUse \n or join two literals with +
Worked Example 7 Compile errors

An Escape Sequence That Does Not Exist

A student tries to print the cheering emoticon Yay \o/. Explain the error and fix it.

Code that does not compile
System.out.println("Yay \o/");
  1. 1The problem. Inside a string, a backslash always starts an escape sequence. \o is not an escape sequence Java recognizes, so the compiler reports an error instead of printing a backslash.
  2. 2The fix. Double the backslash.
    Fixed
    System.out.println("Yay \\o/");
    Output
    Yay \o/
Result: "Yay \\o/" prints Yay \o/. A single backslash is never printed as itself.
Common Mistake 3 · Confusing the Empty String With null

"" 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.

Common Mistake 4 · Treating Quoted Digits as Numbers

"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.

Core Synthesis

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.