Sub topic 1
Creating Strings and Writing Literals
Creating strings and writing literals
A String is a Java object that holds text. An object is a value created from a class, which describes what the object can do.
A string literal is text written between double quotes in Java code. For example, "cat" is a string literal.
An escape sequence starts with a backslash and represents a special character. In a string, \n creates a new line, and \" adds a double quote without ending the literal.
Why strings are immutable
A String is immutable, which means its text cannot change after it is created. A method such as toUpperCase() returns a new String. The original stays the same.
A variable is a named place that holds a value. You can assign a new String to a variable, but that does not change the old String.
Null versus empty text
An empty string, written "", is a String with no text. Its length is zero.
The value null means that a variable refers to no object. It is not an empty string.
Comparing string contents
Use equals() to compare the text inside strings. For example, "cat".equals(word) checks whether word contains the same text. Calling equals() on the literal is also safe if word is null.
For String variables, == checks whether they refer to the same object, not whether their text matches. Use == to check for null, but use equals() to compare text.
Length, char values, and UTF-16 indexes
An index is a position in a string. Indexes start at zero, so charAt(0) gets the first char. A char is a Java value holding one UTF-16 code unit, a 16-bit piece used to represent text. An index outside the string causes an error.
String length counts these code units, not always the characters you see. For example, the emoji in "A😀" takes two code units, so the string has length three.
Try it
Save this program as StringIntro.java:
class StringIntro {
public static void main(String[] args) {
String message = "Hi, \"Ada\"!\nWelcome.";
System.out.println(message);
String word = "cat";
String upper = word.toUpperCase();
System.out.println(word);
System.out.println(upper);
String missing = null;
String empty = "";
System.out.println(missing == null);
System.out.println(empty.length());
System.out.println("cat".equals(word));
String text = "A😀";
System.out.println(text.length());
System.out.println(text.charAt(0));
}
}Compile and run it:
javac -encoding UTF-8 StringIntro.java
java StringIntroThe output is:
Hi, "Ada"!
Welcome.
cat
CAT
true
0
true
3
AExercise
Why does word still contain "cat" after toUpperCase() runs?
Show answer
Strings are immutable. The method creates a new String, which is stored in upper.