Sub topic 1
Creating Strings and Writing Literals
Java programs often need to work with text: a person’s name, a message, or a file path. Java uses the String type for this text.
In this chapter, you will create strings directly in Java code and use special notation for quotes, line breaks, and other characters.
Create a string literal
A string literal is text written directly in Java code between double quotation marks:
"Hello, Ada!"
The quotation marks tell Java where the literal starts and ends. They are not part of the text. The value is Hello, Ada!, without the surrounding marks.
You can store that value in a variable, a named place for a value:
String greeting = "Hello, Ada!";
Here is what each part means:
Stringis the type, which tells Java what kind of value the variable holds. The capitalSmatters.greetingis the variable’s name.=gives the variable its value."Hello, Ada!"is the string literal.;marks the end of the statement.
A class is a group of related Java code. String is a class provided by Java, and a string value is an object created from that class. An object is a value that can hold data and provide ways to work with it.
A string can contain no characters at all:
String empty = "";
It can also contain spaces or numbers. In String room = "204";, the value is text, not a number used for arithmetic.
Run a first example
The following program creates several strings and prints them. A method is a named set of instructions. Java starts this program by running its main method. The println method prints a value and then ends the output line.
Save this code in a file named StringLiterals.java:
class StringLiterals {
public static void main(String[] args) {
String name = "Ada";
String greeting = "Hello, Ada!";
String quoted = "She said, \"Hi!\"";
String path = "C:\\notes\\plan.txt";
String lines = "First line\nSecond line";
String letter = "\u0041";
System.out.println(name);
System.out.println(greeting);
System.out.println(quoted);
System.out.println(path);
System.out.println(lines);
System.out.println(letter);
}
}You need a Java Development Kit, or JDK, to run the example. A JDK includes the tools for preparing and running Java programs.
Open a terminal in the folder containing the file. A terminal is a place where you enter commands. Run:
javac StringLiterals.java
java StringLiteralsThe first command compiles the code: it prepares the program for Java to run. The second command runs it. The output is:
Ada
Hello, Ada!
She said, "Hi!"
C:\notes\plan.txt
First line
Second line
ASome values in the code look different from their output. The next sections explain why.
Write special characters with escapes
An escape sequence is a backslash followed by one or more characters that have a special meaning in Java source code. It lets you write characters that would otherwise be hard to include in a literal.
| In the literal | Meaning in the string |
|---|---|
| `\"` | A double quotation mark |
| `\\` | A backslash |
| `\n` | A line feed, which starts a new line |
| `\t` | A tab, which moves to the next tab position |
| `\r` | A carriage return, which moves back to the start of the line |
| `\b` | A backspace |
| `\f` | A form feed, traditionally used as a page break |
| `\'` | A single quotation mark |
How a terminal displays a tab, backspace, carriage return, or form feed can vary. For everyday messages, quotes, backslashes, and new lines are especially useful.
Put quotation marks inside text
In the example, this line contains quotation marks in the message:
String quoted = "She said, \"Hi!\"";
The outer double quotes mark the start and end of the literal. The escaped quotes, \", become part of the value. Without their backslashes, Java would treat them as the end or start of a literal instead.
Single quotes do not need an escape inside a string. Both "Ada's book" and "Ada\'s book" work, but the first is easier to read.
Put backslashes inside text
A backslash starts an escape sequence, so write \\ when you want one backslash in the value.
For example, the path literal in the program is:
"C:\\notes\\plan.txt"
Its value contains C:\notes\plan.txt. Each pair of backslashes in the code produces one backslash in the text.
Writing "C:\notes\plan.txt" would not give that path. Java would read \n as a line feed, and \p is not a valid escape sequence. Java would report an error.
Start a new line
The literal "First line\nSecond line" holds a line feed between the two phrases. When the example prints it, Second line appears on the next line.
There is a difference between "\n" and "\\n":
"\n"contains a line feed."\\n"contains a backslash followed by the lettern.
Escape sequences are part of how you write a literal in source code. If a person types a backslash and n into a running program, those typed characters do not automatically become a line feed.
Write a Unicode escape
Unicode is a standard that assigns numbers to characters. Java lets you write a Unicode escape in source code using \u followed by exactly four hexadecimal digits. A hexadecimal digit is 0 through 9 or A through F.
In the example:
String letter = "\u0041";
\u0041 represents the letter A, so the program prints A.
Java handles Unicode escapes very early, before it reads the rest of the code as string literals. This makes some Unicode escapes surprising: for a line break inside a string, use \n, not \u000A. The latter becomes a line break too early and breaks the literal.
Write multiple lines with a text block
For longer text, Java 15 and later provide a text block: a way to write a string across several lines. It starts and ends with three double quotes.
Save this example as TextBlockExample.java:
class TextBlockExample {
public static void main(String[] args) {
String message = """
Dear Ada,
Welcome to the class.
""";
System.out.print(message);
}
}Run it with:
javac TextBlockExample.java
java TextBlockExampleThe output is:
Dear Ada,
Welcome to the class.The opening """ must be followed by a line break. Java removes the common indentation used to position the text inside the code. The closing """ is on its own line here, so the string also ends with a line break. The example uses print rather than println because that final line break is already present.
Text blocks are still strings. Escape sequences such as \n and \" can be used in them. If you use a Java version older than 15, use ordinary quoted literals instead.
Check for common mistakes
When Java reports a problem in a string literal, check these points:
- Use
String, notstring. Java names are case-sensitive. - Use double quotes around the text, and close them.
- End the statement with a semicolon.
- Escape a double quote inside the text as
\". - Write a backslash in the value as
\\. - Keep an ordinary quoted literal on one source line. Use
\nfor a line break in its value, or use a text block.
Practice
Exercise
What value does the literal "Say \"hello\"" represent?
Show answer
It represents Say "hello", including the two quotation marks around hello.
Exercise
How would you write a Java literal for the path D:\work\notes.txt?
Show answer
Write "D:\\work\\notes.txt". Each pair of backslashes in the literal represents one backslash in the value.
Exercise
What is the difference between the values written as "\n" and "\\n"?
Show answer
The first contains a line feed. The second contains two characters: a backslash and the letter n.