Sub topic 1
Creating Strings and Writing Literals
A Java program uses a String to hold text. A string can contain letters, numbers, spaces, and symbols. You can use strings for names, messages, file paths, and many other kinds of text.
Write a string literal
A literal is a value written directly in your code. To write a string literal, put its text between double quotation marks:
class FirstString {
public static void main(String[] args) {
String name = "Ada";
System.out.println(name);
}
}A variable is a named place to keep a value. In this example, name is a variable that holds the string "Ada". The word String is its type, which tells Java what kind of value it holds.
System.out.println displays the value and then moves to a new line. The program prints:
AdaJava is case-sensitive, so write String with a capital S. The semicolon marks the end of the statement.
The quotation marks are not part of the text. Spaces inside them are part of the text: "Ada " has a space after the name. You can also write an empty string as "".
Write special characters
What if the text itself needs a double quote? Java needs a way to tell that quote apart from the one that ends the literal.
An escape sequence is a backslash followed by one or more characters. Java reads the sequence as part of the string’s value.
| Escape sequence | What it adds to the text |
|---|---|
| `\"` | A double quotation mark |
| `\\` | A backslash |
| `\n` | A new line |
| `\t` | A tab, which moves the text to a later position on the line |
For example, the literal "Say \"hi\"" contains the text Say "hi". The backslashes tell Java that the inner quotes belong in the text.
To put a backslash in the text, write two backslashes in the literal. This matters for paths such as C:\notes.
Try a complete example
This program creates three strings and prints them. Save it in a file named Welcome.java.
class Welcome {
public static void main(String[] args) {
String visitor = "Ada";
String sign = "She said, \"Welcome!\"\nEnjoy Java.";
String folder = "C:\\notes\\java";
System.out.println(visitor);
System.out.println(sign);
System.out.println(folder);
}
}With the Java tools installed, run these commands in the folder containing the file:
javac Welcome.java
java WelcomeThe output is:
Ada
She said, "Welcome!"
Enjoy Java.
C:\notes\javaThe \n in sign starts a new line in the displayed text. The two \\ sequences in folder each produce one backslash. Java does not print the backslashes used to write \" or \n.
Keep a regular string literal on one line in your code. Use \n when its text needs a new line.
Practice
Exercise
Write a Java statement that stores the text Ada said, "Hi!" in a String variable named message.
Show answer
String message = "Ada said, \"Hi!\"";
Exercise
What does the literal "one\ntwo" contain?
Show answer
It contains "one", a new line, and then "two".