Object-Oriented Programming with Java · Lecture Notes

Chapter 3.4: Strings

Most programs work with text. A user name, an e-mail address, a file path or a message written to the screen is always a piece of text made of characters. In Java such texts are stored in objects of the String class. These notes explain how strings are created, in what order concatenation with + proceeds, and how characters are accessed by index. The most frequently used string methods follow. The immutability of strings, the effect of the locale on Turkish letters and StringBuilder for concatenation in loops are treated in separate sections. After the finer points of reading text from the keyboard with Scanner, the comparison of strings is covered: the difference between == and equals(), the string pool and compareTo. The last sections cover formatted output with printf, the palindrome and word-frequency applications, and common mistakes. All the code in the slides was run with JDK 21; the outputs and error messages are taken from the real runs.

Learning outcomes

Creating strings
Create String objects with string literals and with new; explain how + concatenation is evaluated from left to right.
Index and methods
Reach the parts of a string with charAt, length, indexOf and substring; traverse a string character by character with a loop.
Immutability
Show with memory diagrams that string methods return new objects; know the effect of the locale on case conversion; use StringBuilder in loops.
User input
Explain the difference between next(), nextLine() and nextInt(); avoid the newline trap.
Comparison
Explain the difference between == and equals() with the string pool; use compareTo and the other comparison methods correctly.
Formatted output
Adjust width, alignment and precision with printf and String.format.

3.4.1The string concept

A computer stores all data as numbers. A letter, too, is a number in memory; the char type holds the code of a single character. Real programs, however, work not with single letters but with words and sentences. The name of a student, the description of a product or a reply from a server is a piece of text made of consecutive characters. Java offers a ready-made class for such texts. This section introduces that class and explains how a string is created and how its characters are accessed.

3.4.1.1What is a string?

Definition 3.4.1

A string is an object that stores a piece of text made of characters. In Java the type of strings is the class java.lang.String. Text written between double quotes in the source code, such as "Tarkan", is called a string literal.

A few details in the definition are easily overlooked. First, String is a class, not a primitive type. That is why its name starts with an uppercase letter: int, double and char are written in lowercase, while String has a capital S. A String variable stores not the text itself but the location in memory of the object that holds the text, that is, a reference. Second, the String class is in the java.lang package. This package is added to every program automatically, so no import line is needed. Third, new is not used to write a string literal. The line String name = "Tarkan"; creates the object by itself.

Java stores characters in Unicode. Unicode is the standard that gives a number to the characters of the world's writing systems. Thanks to this, Turkish letters such as ç, ğ, ı, İ, ö, ş and ü sit in a string without trouble. A string actually consists of ordered character boxes. Each box has an ordinal number, and the numbering starts at 0 (Figure 3.4.1).

T0a1r2k3a4n5
Figure 3.4.1: The string "Tarkan" consists of six character boxes. The numbers 0–5 below the boxes are the indices.

A single character and a one-character string are different things. 'T' is written with single quotes and its type is char; in memory it is a two-byte value holding the number 84. "T" is written with double quotes and is a String object of length 1. The two cannot be used in place of each other. The line char c = "T"; does not compile, and neither does String s = 'T';.

The first example in the slides creates three strings and prints them:

String name = "Tarkan";
String fullName = "Mustafa Sandal";
String point = "(" + 3 + ", " + 5 + ")";
System.out.println(name);
System.out.println(fullName);
System.out.println(point);
Tarkan
Mustafa Sandal
(3, 5)

In the first two lines string literals are assigned to variables. A space is also a character: "Mustafa Sandal" is a string of 14 characters. The third line builds a string from numbers. Because "(" is a string, the 3 that follows is converted to text and appended; the same rule works for ", ", 5 and ")". In the end the variable point refers to the text "(3, 5)". This concatenation rule is treated in detail just below, because it is where beginners are most often surprised.

3.4.1.2Creating strings

A string can be created in several ways. The most common is the string literal. Besides it, the constructors of the String class, the String.valueOf method, which turns a number into a string, and the concat method, which joins two strings end to end, are also used. The first half of the code in the slides shows these ways together:

String s0 = "Giresun";            // string literal
char[] letters = {'J', 'a', 'v', 'a'};
String s1 = new String(letters);  // char[]
String s2 = String.valueOf(42);   // from a number
String s3 = "Giresun".concat(" Üni.");
System.out.println(s1 + " " + s2 + " " + s3);

System.out.println("Total: " + 3 + 5);
System.out.println("Total: " + (3 + 5));
System.out.println(3 + 5 + " apples");
System.out.println('a' + 'b' + "c");
System.out.println("" + 'a' + 'b');
Java 42 Giresun Üni.
Total: 35
Total: 8
8 apples
195c
ab

The first six lines of the code work as follows:

  • String s0 = "Giresun"; is the most common form: the string literal is assigned directly to the variable.
  • new String(letters) builds a new string from the characters in a char array. Because the array is {'J', 'a', 'v', 'a'}, s1 becomes "Java". This constructor is useful for turning a text whose characters are computed one by one into a string.
  • String.valueOf(42) returns the text form of the number 42, that is, the string "42". valueOf is a class method: it is called not through an object but with the class name.
  • "Giresun".concat(" Üni.") joins two strings and returns "Giresun Üni.". Here the method is called directly on a string literal; this is valid because a literal is an object too.

The printing line joins these three strings with spaces between them: Java 42 Giresun Üni.. The second half of the code shows the behavior of the + operator. The Total: 35 on the second line of the output surprises most students; the reason is the subject of the next subsection.

The form new String("Giresun") also compiles and runs, but it produces an unnecessary object. This form will be used in the comparison section to explain the string pool. In everyday code there is no benefit in writing new to create a string from a literal.

3.4.1.3Concatenation and the order of the + operator

Definition 3.4.2

String concatenation means producing a new string by joining two values end to end. In Java, if at least one of the operands of the + operator is a String, the other operand is also converted to a string and the two texts are joined. If both operands are numbers, + performs numeric addition.

The same + sign does two different jobs: addition and concatenation. Which one is done is decided separately for each operation. Only the types of the two operands at that moment are looked at. Also, + is evaluated from left to right. That is, the expression a + b + c is computed as (a + b) + c. Considered together, these two rules explain all the outputs in the slides:

  • "Total: " + 3 + 5: first "Total: " + 3 is computed. Because the left side is a string, 3 is converted to text: "Total: 3". Then comes "Total: 3" + 5, and concatenation is done again. The result is Total: 35.
  • "Total: " + (3 + 5): the parentheses are computed first. Since both operands inside are int, addition is performed and 8 comes out. Then 8 is appended to the string: Total: 8.
  • 3 + 5 + " apples": the two operands on the left are numbers and are added first, giving 8. Only after that is a string met: 8 apples.
  • 'a' + 'b' + "c": char is a numeric type. When two chars are added, their codes are added: 97 + 98 = 195. Then "c" is appended: 195c.
  • "" + 'a' + 'b': the empty string at the start changes everything. "" + 'a' is already a string, "a". Then 'b' is appended as text: ab.

In short the rule is this: the expression is read from left to right. Until a string is met, numbers are added. Every + after the moment a string appears is concatenation. If numbers are to be added, parentheses are used.

The trace slide in the slides shows the same rule with variables:

int a = 4, b = 2;
String s1 = "Result: " + a + b;
String s2 = "Result: " + (a + b);
String s3 = a + b + " pens";
String s4 = 'x' + 'y' + "z";
String s5 = "" + 'x' + 'y';
System.out.println(s1 + " | " + s2);
System.out.println(s3 + " | " + s4 + " | " + s5);
Result: 42 | Result: 6
6 pens | 241z | xy

Each row of Table 3.4.1 shows one + operation. The columns give the types of the operands and the result of that step.

Table 3.4.1: The kind and result of each + operation when a = 4 and b = 2. The operations are performed from left to right.
VariableOperationLeft operandRight operandResult
s1"Result: " + aStringintconcatenation: "Result: 4"
… + bStringintconcatenation: "Result: 42"
s2(a + b)intintaddition: 6
"Result: " + 6Stringintconcatenation: "Result: 6"
s3a + bintintaddition: 6
6 + " pens"intStringconcatenation: "6 pens"
s4'x' + 'y'charcharaddition: 120 + 121 = 241
241 + "z"intStringconcatenation: "241z"
s5"" + 'x'Stringcharconcatenation: "x"
"x" + 'y'Stringcharconcatenation: "xy"

The difference between s1 and s2 rests on a single pair of parentheses, but the results differ as much as 42 and 6. Figure 3.4.2 shows the first steps of these two lines with the drawings from the slides. Under the upper boxes are the types of the operands, and in the lower box are the result of that step and its type.

"Result: "String4int+"Result: 4" (String) "Result: 4"String2int+"Result: 42" (String) 4int2int+6 (int) "Result: "String6int+"Result: 6" (String)
Figure 3.4.2: The steps of lines s1 and s2. (a) Because the left side is a String, 4 is appended to the text. (b) The result is still a String; 2 is appended as text too and "Result: 42" comes out. (c) Inside the parentheses two ints are added and the result is 6. (d) 6 is appended to the string.

The line s4 needs separate attention. Although char values look like text, Java handles them as numbers. The Unicode code of the character 'x' is 120 and that of 'y' is 121. When two chars are added side by side the result is an int, 241. This number is converted to text only when "z" is met. In s5, on the other hand, the "" at the start turns the first operation into concatenation, and the two letters come side by side as text. Putting an empty string in front is a common way of joining characters. The same job is also done with String.valueOf('x') + 'y'.

Common mistake

Forgetting the parentheses when printing a sum: the line System.out.println("Total: " + x + y); does not add x and y, it writes them side by side. With x = 10, y = 5 the output is Total: 105. The correct form is "Total: " + (x + y). The compiler misses the error, because both forms are valid Java.

One more detail: concatenation produces a new String object every time. In the expression "Result: " + a + b two intermediate strings are logically created. For a small number of pieces this does not matter. When concatenation is done thousands of times in a loop, the cost grows quickly. This cost is computed in the immutability section.

3.4.1.4Indexing

Definition 3.4.3

The index is the ordinal number of a character in the string. The index of the first character is 0 and that of the last character is length() - 1. Accessing a character by its index is called indexing.

Indexing has two basic methods. length() returns the number of characters in the string. charAt(i) gives the character at index i as a char. "Tarkan" has six characters; its indices run from 0 to 5 (Figure 3.4.3). Although the length is 6, there is no character number 6. Because numbering starts at 0, the last index is always one less than the length.

T0a1r2k3a4n5charAt(0)charAt(5)length() = 6
Figure 3.4.3: The first character is obtained with charAt(0) and the last with charAt(length() - 1), that is, charAt(5).

The example in the slides tries these methods on "Tarkan":

String name = "Tarkan";
System.out.println(name.length());
System.out.println(name.charAt(0));
System.out.println(name.charAt(name.length() - 1));
char c = name.charAt(2);
System.out.println(c + 1);
System.out.println((char) (c + 1));
6
T
n
115
s

The first line prints the length, 6. charAt(0) gives the first letter, T. For the last letter the index is not written by hand but computed from the length: name.length() - 1 = 5 and charAt(5) = n. This form works for strings of any length. On the next line c takes the character 'r' at index 2.

The last two lines show that char is a number. The Unicode code of the character 'r' is 114. In the expression c + 1 a char and an int are added and the result is an int: 115. A number, not a letter, appears on the screen. To see the next letter, the result is converted back with (char): the character with code 115 is s. Simple encryption examples based on shifting letters use this conversion.

length() is a method, that is, it has parentheses at the end. For arrays, on the other hand, the length is a field and is written without parentheses: arr.length. The two forms are often confused and both give a compile error:

StringLength.java:4: error: cannot find symbol
        int n = s.length;
                 ^
  symbol:   variable length
  location: variable s of type String
ArrayLength.java:4: error: cannot find symbol
        int n = d.length();
                 ^
  symbol:   method length()
  location: variable d of type int[]

The symbol line in the messages tells the difference clearly. In the first, the compiler looks for a variable named length in String and cannot find it. In the second it looks for a method named length() in int[] and again cannot find it. Another confusion is trying to access a string with square brackets like an array. The form s[0] works in C and Python but does not compile in Java:

Arr.java:4: error: array required, but String found
        char c = s[0];
                  ^

An invalid index is not caught at compile time, because the value of an index is usually known only while the program runs. An index that goes beyond the string causes an exception at run time:

String s = "Java";
System.out.println(s.charAt(4));
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
    Index 4 out of bounds for length 4

"Java" has four characters; the valid indices are 0, 1, 2 and 3. The call charAt(4) throws StringIndexOutOfBoundsException and the program stops. The words “Index 4 out of bounds for length 4” in the message give the place of the problem exactly: index 4 was requested, while the length is 4. A negative index causes the same exception; for "Java".charAt(-1) the message is “Index -1 out of bounds for length 4”.

Common mistake

Trying to get the last character with s.charAt(s.length()). The length is one more than the last index, and this call throws StringIndexOutOfBoundsException on every string. The same error is made in a loop with the condition i <= s.length(). The correct condition is i < s.length().

3.4.1.5Looping over characters

To look at all the characters of a string one by one, a for loop is used. The loop variable starts at 0 and stops before reaching the length. The program in the slides takes a word from the user and prints the letters of that word at odd positions; the loop variable increases by 2 on every pass:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
String word = scanner.nextLine();
for (int i = 0; i < word.length(); i += 2) {
  char letter = word.charAt(i);
  System.out.println((i + 1) + ". letter: " + letter);
}
scanner.close();

The program reads a line from the keyboard with Scanner. To use Scanner, the line import java.util.Scanner; is added at the top of the file; the details of the reading methods are in the user input section. Unlike println, print does not move to the next line. That is why the word the user types appears on the same line as the prompt. When the user types Giresun and presses Enter, the output is as follows:

Enter a word: Giresun
1. letter: G
3. letter: r
5. letter: s
7. letter: n

Table 3.4.2 gives every pass of the loop. "Giresun" has seven characters; its indices run from 0 to 6. The loop variable takes the values 0, 2, 4, 6. So that the ordinal number written on the screen starts at 1, as people are used to, i + 1 is printed. The parentheses here are needed: (i + 1) + ". letter: " does the addition first. In this line the result would be the same without the parentheses, because the expression starts with a number. Still, the parentheses show clearly that the addition is done before the concatenation. In an expression that starts with a string, such as "Letter " + i + 1, writing it without parentheses produces Letter 01 instead of Letter 1 when i = 0.

Table 3.4.2: Tracing the loop for word = "Giresun" (length 7).
Passii < 7charAt(i)Line written
10true'G'1. letter: G
22true'r'3. letter: r
34true's'5. letter: s
46true'n'7. letter: n
—8false—the loop ends

The last row is important. When i is 8, the condition is false and charAt(8) is never called. Because the condition is written as i < word.length(), the loop stops safely at any length. If the word had an even length, for example "Ordu", the loop would read indices 0 and 2 and end at i = 4. If an empty line is entered, the length is 0 and the body never runs.

At the end of the loop scanner.close() is called. This call releases the resource used by the Scanner. When a Scanner that reads from the keyboard is closed, System.in is closed too, and the rest of the program can no longer read from the keyboard. That is why close() is called only after all the reading is done.

3.4.2String methods

The String class offers ready-made methods for most everyday jobs with text: searching for a word, taking a part of the text, making letters uppercase, removing spaces, splitting the text into pieces. All these methods are called with a dot on a string object: s.length(), s.indexOf("a"). They also share one more property: none of them changes the string it is called on. The result always comes back as a new value.

3.4.2.1Basic methods

Table 3.4.3 shows the most frequently used methods on the string s = "Java Programming". This string has 16 characters; the space at index 4 counts as a character too. All the results in the table were obtained by running with JDK 21.

Table 3.4.3: Basic string methods, for s = "Java Programming".
MethodWhat does it do?Example and result
length()Returns the number of characters.s.length() → 16
charAt(i)Returns the character at index i (char).s.charAt(0) → 'J'
indexOf(str)The index where the substring first starts; −1 if it is not found.s.indexOf("Programming") → 5
s.indexOf("C++") → −1
indexOf(str, from)Starts the search at index from.s.indexOf("a", 4) → 10
lastIndexOf(str)The index of the last occurrence.s.lastIndexOf('a') → 15
substring(i1, i2)The substring in between, with i1 included and i2 excluded.s.substring(5, 12) → "Program"
substring(i1)From i1 to the end.s.substring(5) → "Programming"
toLowerCase()A new lowercase string."java programming"
toUpperCase()A new uppercase string."JAVA PROGRAMMING"
Definition 3.4.4

A substring is a part of a string made of consecutive characters. s.substring(a, b) returns the part of s that starts at index a and ends at index b - 1. The length of the part is b - a.

indexOf is a search method. It scans the string from start to end and gives the starting index of the first occurrence of the text sought. If the text does not occur at all, it returns −1. Because −1 cannot be a valid index, it carries the meaning “not found” safely. That is why the result of a search is often checked before use, in the form if (s.indexOf(x) != -1). The two-parameter version of the method starts the search from a given index. The call s.indexOf("a", 4) skips the as at 1 and 3 and first finds the a at index 10. lastIndexOf, on the other hand, scans the string from end to start and gives the last match. indexOf and lastIndexOf accept both a string and a single character ('a').

The most confused aspect of substring is that the end index is excluded. This rule has two practical benefits. First, the length of the part is the difference of the two indices: substring(5, 12) gives 12 − 5 = 7 characters. Second, consecutive parts fit side by side easily: s.substring(0, k) + s.substring(k) gives s itself for every k. The one-parameter substring(5) is the same as substring(5, s.length()).

If an invalid range is given, substring also throws StringIndexOutOfBoundsException. The end cannot be greater than the length, and the start cannot be greater than the end. The message for the call "Java".substring(2, 6) gives the range in the half-open interval notation of mathematics:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
    Range [2, 6) out of bounds for length 4

The notation [2, 6) in the message means “2 included, 6 excluded”. This notation also summarizes the rule of substring. On the other hand, s.substring(s.length()) is valid and returns the empty string. Equal start and end mean an empty range.

3.4.2.2indexOf and substring step by step

The trace slide in the slides runs the methods in the table in order and shows the value each variable gets on the character boxes:

String str = "Java Programming";
int index = str.indexOf("Programming");
int length = str.length();
String lo = str.substring(5, 12);
String last = str.substring(5);
String lower = str.toLowerCase();
String upper = str.toUpperCase();

Nothing is printed in the code; what matters is the values the variables get after each line. Table 3.4.4 gives these values in order.

Table 3.4.4: The value produced after each line on str = "Java Programming".
LineVariableValueExplanation
2index5"Programming" starts at index 5
3length16indices 0 … 15
4lo"Program"indices 5 … 11; 12 − 5 = 7 characters
5last"Programlama"from index 5 to the end
6lower"java programming"a new string; str has not changed
7upper"JAVA PROGRAMMING"a new string; str has not changed

Figure 3.4.4 shows two important steps with a drawing. The highlighted boxes are the characters the method reaches. In the substring(5, 12) step box number 12 (g) is not highlighted; the fact that the end index is excluded is visible in the drawing as well.

J0a1v2a3␣4P5r6o7g8r9a10m11l12a13m14a155 ← first match J0a1v2a3␣4P5r6o7g8r9a10m11l12a13m14a155 included12 excluded
Figure 3.4.4: (a) indexOf("Programming") gives the index where the match starts, 5. (b) substring(5, 12) takes indices 5–11: "Program".

In the last two lines toLowerCase() and toUpperCase() are called. Both return a new string, and this string is assigned to another variable. The variable str stays "Java Programming" throughout the program. The impression that a method “changes the string” is misleading; the reason is explained in the immutability section.

Example 3.4.1

Let us split an e-mail address into a user name and a domain name. Let the address be e = "student@giresun.edu.tr". The position of the @ sign is found with int at = e.indexOf('@');. "student" has seven letters; the letters occupy indices 0–6 and @ is at index 7. The user name is the part before the @: e.substring(0, at) = e.substring(0, 7) = student. Because the end index is excluded, the @ does not enter the part. The domain name is the part after the @: e.substring(at + 1) = e.substring(8) = giresun.edu.tr. Had the + 1 been forgotten here, the result would have been @giresun.edu.tr. The method is independent of the length of the address; the indices are not counted by hand but found with indexOf.

3.4.2.3Other useful methods

Besides the basic methods, a few more methods are frequent in everyday code. The example in the slides tries them together:

String s = "  Hello World  ";
System.out.println("[" + s.trim() + "]");
System.out.println("[" + s.replace('o', '0') + "]");
String[] fruits = "apple,pear,plum".split(",");
System.out.println(fruits.length);
System.out.println(fruits[1]);
System.out.println(String.join(" - ", fruits));
System.out.println("ab".repeat(3));       // Java 11+
System.out.println("".isEmpty());
System.out.println("   ".isBlank());      // Java 11+
char[] arr = "Java".toCharArray();
System.out.println(arr.length + " " + arr[0]);
System.out.println("Giresun".replace("sun", "SUN"));
System.out.println(String.valueOf(3.5) + 1);
System.out.println(Integer.parseInt("42") + 1);
[Hello World]
[  Hell0 W0rld  ]
3
pear
apple - pear - plum
ababab
true
true
4 J
GireSUN
3.51
43

Let us explain the lines in order:

  • trim() removes the spaces at the start and end of the string. It does not touch the spaces in between: " Hello World " → [Hello World]. The square brackets were added to make the spaces visible. Calling trim() before processing user input is a common habit. strip(), which came with Java 11, does the same job for all the whitespace characters in Unicode.
  • replace('o', '0') turns all the o letters into 0: [ Hell0 W0rld ]. It changes not only the first match but all of them. The spaces are preserved, because replace produces the new string from s itself. The result of trim() on the previous line was not assigned anywhere.
  • split(",") splits the string at the given separator and returns the pieces as a String[] array. "apple,pear,plum" is split into three pieces; fruits.length is 3 and fruits[1] is pear.
  • String.join(" - ", fruits) does the opposite of splitting: it joins the pieces with the separator between them. The result is apple - pear - plum.
  • "ab".repeat(3) writes the string three times side by side: ababab. This method was added in Java 11.
  • isEmpty() returns true if the length is 0. isBlank() (Java 11) returns true if the string is empty or consists only of whitespace characters. " " is not empty but consists of nothing except spaces: isEmpty() gives false and isBlank() gives true.
  • toCharArray() copies the characters of the string into a new char array. The length of the array is 4 and its first element is 'J'. The array can be changed; so jobs such as swapping characters can be done on the array and the result converted back with new String(arr).
  • replace is not limited to a single character; it also takes strings: "Giresun".replace("sun", "SUN") → GireSUN.
  • The last two lines show the conversion between numbers and strings. String.valueOf(3.5) is a string, "3.5"; adding 1 to it is concatenation and the result is 3.51. Integer.parseInt("42") converts the string into a real int; when 1 is added, 43 comes out. For floating-point numbers Double.parseDouble is used.

parseInt accepts only a string made of digits (and an optional sign at the start). If a text containing spaces or letters is given, it throws NumberFormatException:

Exception in thread "main" java.lang.NumberFormatException:
    For input string: " 12 "

That is why number text coming from a user or a file is first cleaned with trim(): Integer.parseInt(text.trim()). This step matters even more when used together with splitting. When a line such as " 3, 12 " is split at the comma, spaces are left at the start and end of the pieces.

split has two more subtleties. An empty piece is produced between two consecutive separators. Empty pieces at the end of the string, however, are dropped. Also, the parameter of split is a regular expression: a pattern language used in text searching. The pattern " +" means “one or more spaces”:

System.out.println(Arrays.toString("a b  c".split(" ")));
System.out.println(Arrays.toString("a b  c".split(" +")));
System.out.println(Arrays.toString("a,,b,".split(",")));
[a, b, , c]
[a, b, c]
[a, , b]

In the first line two consecutive spaces produce an empty piece and the array has four elements. The second line counts several spaces as a single separator. In the third line the empty piece in the middle remains and the one at the end is dropped; the array has three elements. The dot (.) and the vertical bar (|) have special meanings in regular expressions. That is why "a.b".split(".") does not give the expected result; to split at the dot, split("\\.") is written.

3.4.3Immutability

In the earlier sections it was stressed several times that every method returns a new value. This is not a coincidence but the basic design decision of the String class. This section explains what the decision means, how it looks in memory, and the cost it brings. The pitfalls of case conversion in Turkish texts and the StringBuilder class, designed for large numbers of concatenations, are also in this section.

3.4.3.1An immutable object

Definition 3.4.5

An immutable object is an object whose state never changes after it is created. String objects are immutable: the characters and the length of a string are fixed at the moment the object is created and never change afterwards. toUpperCase, replace, substring, concat and + do not touch the original object; they return the result as a new object.

An analogy helps. A string is like a stone tablet. The writing on the tablet cannot be scraped off and corrected. If a change is needed, a new tablet is written and put in place of the old one. The example in the slides shows this behavior:

String s = "Giresun Üniversitesi";
s.toUpperCase();      // the result is lost
System.out.println(s);
s = s.toUpperCase();  // the result is assigned to s
System.out.println(s);
Giresun Üniversitesi
GİRESUN ÜNİVERSİTESİ

The call s.toUpperCase(); on the second line runs and produces a new uppercase string. But the result is assigned to no variable and is lost. That is why the first println prints the original text. On the fourth line the result is assigned to s. Here too the old object does not change; the variable s now points to the new object. What changes is not the object but the place the variable points to.

Figure 3.4.5 gives these two cases with a memory drawing. The stack in the left part holds the local variables of the method; s sits here. The heap on the right is the region where objects live. The arrow leaving the variable s points to the object it refers to.

StackHeapmain()string pool"Giresun Üniversitesi""GİRESUN ÜNİVERSİTESİ"s StackHeapmain()string pool"Giresun Üniversitesi""GİRESUN ÜNİVERSİTESİ""GİRESUN ÜNİVERSİTESİ"s StackHeapmain()string pool"Giresun Üniversitesi""GİRESUN ÜNİVERSİTESİ"s
Figure 3.4.5: Immutability in memory. (a) toUpperCase() produces a new object, but because the result is not assigned, s keeps pointing to the old object. (b) The second call again produces a new object and this time its reference is assigned to s. (c) s now points to the uppercase object; the old object stays unchanged.

No variable points to the object produced by the first call. Such objects, which nobody points to, are left to the garbage collector. The garbage collector is the JVM component that reclaims the memory of objects no reference points to when the time comes. The programmer does not have to release this memory by hand.

The GİRESUN ÜNİVERSİTESİ on the second line of the output is written with the dotted capital İ letters. This result is obtained on a computer with the Turkish locale. On a computer with the English locale the same program prints GIRESUN ÜNIVERSITESI. The reason is explained in the next subsection.

Immutability has a price: every change means a new object. The designers of Java accepted this price for the following benefits:

  • Safe sharing. Two variables pointing to the same string cannot corrupt each other. There is no need to fear that a string given to a method will be changed inside that method.
  • The string pool. String literals with the same content can share a single object. Sharing is safe only if the object does not change. The pool is treated in detail in the comparison section.
  • Safety between threads. Parts of a program that run at the same time can share an object that does not change without taking extra precautions.
Common mistake

Forgetting to assign the result of a string method: the lines name.trim();, name.toUpperCase(); or name.replace(" ", ""); do not change name. The compiler gives no warning; the program runs but nothing happens. The correct form is name = name.trim();. For the same reason an attempt to change a character in place, such as s.charAt(0) = 'j';, does not compile.

3.4.3.2Turkish letters and the locale

Definition 3.4.6

A locale is the set of format rules specific to a language and a region: case conversion, decimal separator, thousands separator, date format. In Java it is represented by the class java.util.Locale. The locale for Turkish as spoken in Turkey is tr-TR.

The Turkish alphabet has two forms of the letter i, dotted and dotless, and each has its own uppercase: i ↔ İ, ı ↔ I. In English there is only the pair i ↔ I. The parameterless toUpperCase() and toLowerCase() use the default locale of the computer. The same program can therefore give different results on different machines:

import java.util.Locale;

String s = "Giresun Üniversitesi";
System.out.println(s.toUpperCase());
System.out.println(s.toUpperCase(Locale.ROOT));
System.out.println("TITLE".toLowerCase());
System.out.println("TITLE".toLowerCase().equals("title"));
System.out.println("TITLE".toLowerCase(Locale.ROOT));
GİRESUN ÜNİVERSİTESİ
GIRESUN ÜNIVERSITESI
tıtle
false
title

The output was obtained on a computer set to Turkish. In the first line, since the default locale is Turkish, the i letters become İ. In the second line Locale.ROOT is given. This is the language-independent locale that uses the basic Unicode rules; the i letters become I. The third line shows the trap: when "TITLE" is lowercased with Turkish rules, the I letters become ı and the result is tıtle. The comparison on the fourth line therefore gives false. On the last line the expected title is obtained with Locale.ROOT. Table 3.4.5 summarizes the conversion of four letters in the two locales.

Table 3.4.5: Case conversion in the Turkish (tr) and language-independent (Locale.ROOT) locales.
ConversionTurkish (tr)ROOT / English
i → uppercaseİI
I → lowercaseıi
ı → uppercaseII
İ → lowercaseii̇ (i + combining dot; two characters)

The last row of the table is a less well-known case. When İ is lowercased with non-Turkish rules, the result is not a single i but an i followed by a “combining dot” character. There is no visible difference, but the length of the string increases. "İSTANBUL".toLowerCase(Locale.ROOT) gives a string of 9 characters; "İki".toLowerCase(Locale.ROOT).equals("iki"), on the other hand, is false.

The practical rule is this. In texts inside the program, that is, texts that a machine will read such as command names, file extensions and protocol keys, Locale.ROOT is used. In Turkish texts to be shown to the user, the Turkish locale is given explicitly: text.toUpperCase(Locale.forLanguageTag("tr-TR")). This way the program produces the same result on whatever computer it runs. The Locale class is in the java.util package and needs the line import java.util.Locale;.

Common mistake

Checking user input with input.toLowerCase().equals("exit"). On a computer set to Turkish, if the user types EXIT, the result is "exıt" and the condition does not hold. Because the error appears only on some machines, it is hard to find. To ignore the difference between uppercase and lowercase, equalsIgnoreCase or toLowerCase(Locale.ROOT) is used.

3.4.3.3The cost of concatenating in a loop

The price of immutability is felt most when concatenating in a loop. The first part of the code in the slides collects the numbers from 1 to 5 in a string:

String result = "";
for (int i = 1; i <= 5; i++) {
  result += i + " ";   // a new String on every pass
}
System.out.println(result);

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
  sb.append(i).append(' ');   // the same object grows
}
String text = sb.toString();
System.out.println(text);

StringBuilder rev = new StringBuilder("Giresun");
rev.reverse();
System.out.println(rev);
StringBuilder k = new StringBuilder("Java");
k.insert(0, ">> ").append('!');
k.setCharAt(3, 'j');
System.out.println(k + " " + k.length());
1 2 3 4 5 
1 2 3 4 5 
nuseriG
>> java! 8

In the first loop the line result += i + " "; produces a new String object on every pass. The old content and the new piece are copied into this object, and the old object is left as garbage. The number of characters copied in one pass equals the length of the text accumulated so far. If each pass adds one character, the total number of characters copied is 1 + 2 + … + n = n(n + 1)/2, that is, about n²/2. For example, in a loop of a thousand passes 500,500 characters are copied. This growth is written O(n²): when the number of passes doubles, the work quadruples.

In this example of five passes the difference is not felt. Each pass adds two characters (a digit and a space); a total of 2 + 4 + 6 + 8 + 10 = 30 characters are copied. But if a report of tens of thousands of lines or the contents of a large file are built this way, the program slows down noticeably.

3.4.3.4StringBuilder

Definition 3.4.7

StringBuilder is a mutable character buffer. It contains an array that holds the characters and a length that shows how many cells of this array are filled. Methods such as append, insert, reverse, setCharAt and deleteCharAt do not produce a new object; they change the contents of the same object. When the job is done, a String is obtained with toString().

The second part of the code builds the same text with StringBuilder. sb.append(i).append(' ') adds a number and a space to the end of the buffer on every pass. The buffer is a single object and grows as needed. When the loop ends, sb.toString() produces a String from the contents. The output of the two methods is the same: 1 2 3 4 5 (with a space at the end).

The append method returns the buffer itself. That is why the calls can be written one after another like a chain: sb.append(i).append(' '). The first append returns sb, and the second append again works on sb. append has a separate version for each primitive type and for String; numbers, characters and booleans are all converted to text and appended.

The last part of the code tries the other methods. new StringBuilder("Giresun") creates a buffer whose content is "Giresun". reverse() reverses the buffer in place and nuseriG is printed. When a StringBuilder is given to println, toString() is called automatically. In the last example three characters are inserted at the start of the "Java" buffer with insert(0, ">> "), '!' is put at the end, and the J at index 3 is turned into j with setCharAt. The result is >> java! and the length is 8. This operation is not possible with String; to change a character, a new string has to be built every time.

The trace slide in the slides shows the inside of the buffer cell by cell:

StringBuilder sb = new StringBuilder("Java");
sb.append(' ').append(8);
sb.insert(0, ">> ");
sb.setCharAt(3, 'j');
sb.deleteCharAt(sb.length() - 1);
sb.append("programming book");
String s = sb.toString();
System.out.println(s + " " + sb.length() + " " + sb.capacity());
>> java programming book 24 42

A StringBuilder has two measures. The length (length()) is the number of filled cells. The capacity (capacity()) is the total number of cells of the internal array. The capacity of a buffer created from a string is found by adding 16 to the length of the string. For "Java" this is 4 + 16 = 20. The capacity of an empty new StringBuilder() is 16. Table 3.4.6 gives the state after each line; the values were verified by printing length() and capacity().

Table 3.4.6: StringBuilder trace. The text in square brackets is the filled part of the buffer.
LineContentLengthCapacityExplanation
new StringBuilder("Java")[Java]42016 + 4
append(' ').append(8)[Java 8]620appended at the end, the object is the same
insert(0, ">> ")[>> Java 8]920the old characters shift 3 cells to the right
setCharAt(3, 'j')[>> java 8]920index 3 is changed in place
deleteCharAt(length() - 1)[>> java ]820the 8 at the end is deleted
append("programming book")[>> java programming book]244224 > 20: the buffer grows
toString()—2442a new String from the contents

insert and deleteCharAt are not cheap operations. To insert something at the start, all the following characters must be shifted to the right; deleting from the middle also requires shifting to the left. These shifts do work proportional to the length of the buffer. append, on the other hand, writes only at the end as long as there is room, and finishes in constant time.

The last append adds 16 characters and the length rises to 24. 24 characters do not fit into 20 cells. In this case StringBuilder allocates a new, larger array, copies the old contents into it, and abandons the old array. The rule in the JDK chooses the new capacity as twice the old one plus two: 2 × 20 + 2 = 42. The notation (20 + 1) × 2 in the slides gives the same number. If the required length is greater than that, that length is taken directly. Figure 3.4.6 shows the moment of growth.

>>·Java·8length = 9capacity = 20 >>·java·programlama·dili…length = 24capacity = 4220 → 42: new array, contents copied
Figure 3.4.6: The StringBuilder buffer. (a) After insert(0, ">> "): the old characters have shifted three cells to the right. (b) 24 characters do not fit into 20 cells; the capacity rises to 42 and the contents are copied to the new array.

Why is StringBuilder fast although copying takes place during growth? The capacity roughly doubles at every growth. When characters are added one by one to an empty buffer, the capacity goes 16, 34, 70, 142, 286, 574, 1150. Only six growths are needed to add a thousand characters. The total number of characters copied in these growths does not exceed a few times the number of characters added. So the total cost of adding n characters is O(n); compared with the O(n²) cost of concatenation with +=, the difference is very large.

This does not mean that the + operator should never be used. For concatenations of a few pieces + is readable and fast enough; the Java compiler already translates the concatenations in a single expression efficiently. StringBuilder is preferred when many pieces are joined inside a loop. If the approximate length is known in advance, giving an initial capacity such as new StringBuilder(1000) reduces the number of growths.

3.4.4User input: Scanner

A program often asks the user for information: a name, an age, a sentence. Everything that comes from the keyboard first comes as characters. Converting these characters into a word, a line or a number is the job of the Scanner class. Although the reading methods look alike, their behavior differs in subtle points. If these distinctions are not known, programs produce odd bugs such as skipping the user's question.

3.4.4.1Scanner and the reading methods

Definition 3.4.8

java.util.Scanner is a class that reads the text in a source by splitting it into pieces. new Scanner(System.in) creates an object that reads from the keyboard. The line typed at the keyboard enters an input buffer when Enter is pressed; the newline character (⏎) is also added to the buffer. Scanner keeps a cursor in the buffer, and each read moves the cursor to the end of the part that was read.

Four reading methods are frequently used:

  • next() first skips the leading whitespace (space, tab, newline) and then reads up to the next whitespace. The result is a single word.
  • nextLine() reads everything from where the cursor is to the end of the line. It does not skip spaces. It consumes the newline character but does not include it in the result.
  • nextInt() and nextDouble() skip leading whitespace and read a number. They leave the newline after the number in the buffer. If a letter is typed instead of a number, they throw InputMismatchException.

A program that reads from the keyboard contains the line import java.util.Scanner; at the top of the file. When the reading is finished, keyboard.close() is called. The example in the slides reads one line first as two words and then as the rest of the line:

Scanner keyboard = new Scanner(System.in);
System.out.println("enter some text");
String input = keyboard.next();
System.out.println(input);    // algorithms
input = keyboard.next();
System.out.println(input);    // in
input = keyboard.nextLine();
System.out.println(input);    //  programming lessons

The user types the following line and presses Enter:

algorithms in programming lessons

The program prints:

enter some text
algorithms
in
 programming lessons

The leading space on the last line of the output is noticeable. The space after the word “in” is part of the line, and nextLine() does not skip spaces. That is why the text read is " programming lessons".

3.4.4.2next() and nextLine() step by step

Table 3.4.7 gives where the cursor moves from and to on each read. The indices of the characters in the buffer start at 0: "algorithms" occupies 0–9, the first space 10, "in" 11–12, the second space 13, the remaining text 14–32, and the newline is at 33.

Table 3.4.7: The position of the cursor while reading the line algorithms in programming lessons⏎.
CallCursor beforeReadCursor afterExplanation
next()0"algorithms"10reads up to the first space; the space stays in the buffer
next()10"in"13first skips the space at 10
nextLine()13" programming lessons"34does not skip the space; consumes ⏎ and does not include it in the result

Figure 3.4.7 shows the state of the buffer at the end of the second and third reads. The characters that have been read are faded, and the place of the cursor is marked with a triangle.

Input bufferbilgisayar␣ve␣programlamaya␣giris⏎cursor Input bufferbilgisayar␣ve␣programlamaya␣giris⏎cursor
Figure 3.4.7: The input buffer. (a) The second next() skips the space and reads "in"; the cursor is again in front of a space. (b) nextLine() reads to the end of the line without skipping the space and consumes ⏎.

The result for the programmer is this: for a one-word answer (a first name, a city, a command) next() is used, and for an answer that may contain spaces (a full name, an address, a sentence) nextLine() is used. If a full name is read with next(), only the first name is taken and the surname stays in the buffer and gets mixed into the next read.

3.4.4.3The nextLine() trap after nextInt()

When nextLine() is used right after the methods that read numbers, an error appears that almost every beginner meets. The program in the slides first asks for the age and then for the name:

Scanner keyboard = new Scanner(System.in);
System.out.print("Age: ");
int age = keyboard.nextInt();
System.out.print("Name: ");
String name = keyboard.nextLine();
System.out.println("[" + name + "] " + age);

The user types 19 and presses Enter. The program ends without asking for the name:

Age: 19
Name: [] 19

Why this happens can be understood by looking at the buffer (Figure 3.4.8). The buffer holds 19⏎. nextInt() reads only 19 and leaves the cursor in front of the ⏎. The nextLine() that follows does its job: it reads from the cursor to the end of the line. Since there are no characters between the cursor and the newline, the result is the empty string. nextLine() consumes the ⏎ and returns at once. Before the user has had a chance to type a name, the variable name has become "".

buffer after nextInt()19⏎Ayse⏎cursor in front of ⏎
Figure 3.4.8: After nextInt() reads 19, the cursor waits in front of the newline character.

The solution is to consume the leftover newline with a separate nextLine() call after reading the number:

int age = keyboard.nextInt();
keyboard.nextLine();          // discard the ⏎
System.out.print("Name: ");
String name = keyboard.nextLine();
Age: 19
Name: Ayşe
[Ayşe] 19

The result of the keyboard.nextLine(); call inserted in between is not used; its only job is to clear the ⏎ from the buffer. The nextLine() after that waits for the user's new line. A second solution is to read all the input with nextLine() and convert the numbers yourself: int age = Integer.parseInt(keyboard.nextLine().trim());. With this method no leftover newline is ever left in the buffer.

Example 3.4.2

A program that asks the user first for the age and then for a full name and writes the result with printf is written like this, without falling into the trap:

Scanner k = new Scanner(System.in);
System.out.print("Age: ");
int age = k.nextInt();
k.nextLine();   // discard the newline
System.out.print("Name: ");
String name = k.nextLine();
System.out.printf("Name: %s, Age: %d%n", name, age);

When the user enters 20 and Ali Veli, the console looks like this:

Age: 20
Name: Ali Veli
Name: Ali Veli, Age: 20

nextInt() reads 20, and the ⏎ stays in the buffer. k.nextLine(); consumes this ⏎. The last nextLine() waits for the user's new line and reads "Ali Veli" together with its space. Had next() been used for the full name, only "Ali" would have been read. The printf line is explained in the formatted output section.

3.4.5Comparing strings

Asking whether two strings are the same looks simple. But in Java this question has two different meanings: “do the two variables point to the same object?” and “is the content of the two objects the same?”. The first question is asked with == and the second with equals(). This section explains the difference between the two questions, the string pool that sometimes hides the difference, and the compareTo method used for ordering.

3.4.5.1Comparing with ==

For primitive types such as int, == compares the two values. String variables, however, hold references, not values. So == compares the references of two strings, that is, their addresses in memory, not their contents. If two variables point to the same object, the result is true. Even if the contents are the same, if the objects differ the result is false. The example in the slides:

String str1 = "Giresun";
String str2 = "Giresun";
String str3 = new String("Giresun");
System.out.println(str1 == str2);        // true
System.out.println(str1 == "Giresun");   // true
System.out.println(str1 == str3);        // false
System.out.println(str3 == "Giresun");   // false
true
true
false
false

In all four comparisons the content is always "Giresun", but two of the results are false. That str1 == str2 comes out true is no luck; it is a consequence of the string pool. str3 is a separate object created with new.

3.4.5.2The string pool

Definition 3.4.9

The string pool is the special region where the JVM keeps string literals. All string literals with the same content in the source code share a single object in the pool. new String(...), on the other hand, does not look at the pool; on every call it creates a new object on the heap.

The purpose of the pool is to save memory. The literal "Giresun" may occur in a hundred different places in a program. Instead of creating a new object at each occurrence, all of them point to the same object. This sharing is safe only because strings are immutable. If the code in one place could change the object "Giresun", the other ninety-nine places would be affected too.

Table 3.4.8 gives the pool trace from the slides line by line. The objects are numbered #1 and #2.

Table 3.4.8: The string pool trace. #1 is the object in the pool and #2 is the object outside the pool.
Linestr1str2str3Explanation
String str1 = "Giresun";#1the literal gives #1 in the pool
String str2 = "Giresun";#1#1the same literal: no new object is created
String str3 = new String("Giresun");#1#1#2new produces a new object outside the pool
str1 == str2#1 and #1true
str1 == "Giresun"#1 and #1true
str1 == str3#1 and #2false
str3 == "Giresun"#2 and #1false
StackHeapmain()string pool"Giresun""Giresun"str1str2str3
Figure 3.4.9: The memory after the three declarations. str1 and str2 point to the same object in the pool, and str3 points to a separate object outside the pool.

Strings that enter the pool are not limited to the literals in the source code. Expressions that can be computed at compile time are also treated as constants. Both sides of the expression "Gire" + "sun" are constants; the compiler writes it directly as "Giresun" and the result points to the object in the pool. A concatenation with a variable on one side is done at run time and produces a new object. A variable defined with final and initialized with a constant is a constant for the compiler:

String str1 = "Giresun";
String a = "Gire";
final String fa = "Gire";
System.out.println((a + "sun") == str1);   // false
System.out.println((fa + "sun") == str1);  // true

The intern() method returns the pool counterpart of a string. If an object with the same content exists in the pool, the reference of that object is returned; if not, the string is added to the pool and itself is returned. str3.intern() == str1 is therefore true. intern() is rarely needed in everyday code; its existence helps to understand how the pool works.

If you want to follow the pool and immutability step by step, you can use the String Pool simulator on the course site. The simulator visually shows how literals enter the pool, the separate objects created with new String, and the in-place change of a StringBuilder buffer.

3.4.5.3Comparing content with equals()

Definition 3.4.10

a.equals(b) compares the contents of the strings a and b character by character. If the lengths and the character at every position are the same, it returns true. It does not look at whether the objects are the same. If b is null, it returns false.

The example in the slides compares the same three variables, this time with equals, and adds a few cases:

String str1 = "Giresun";
String str2 = "Giresun";
String str3 = new String("Giresun");
System.out.println(str1.equals(str2));
System.out.println(str1.equals("Giresun"));
System.out.println(str1.equals(str3));
System.out.println(str3.equals("Giresun"));
System.out.println(str3.intern() == str1);
String a = "Gire";
String b = a + "sun";  // new object
System.out.println(b == str1);
System.out.println(b.equals(str1));
true
true
true
true
true
false
true

The first four lines give true whichever way the object was created; the content is always "Giresun". The fifth line shows that intern() returns the pool counterpart. In the last two lines b is formed by joining the variable a and the constant "sun" at run time. The resulting object is new: b == str1 is false and b.equals(str1) is true.

In practice the most dangerous case is user input. A string read from a Scanner is created at run time and is always a new object. So the condition input == "yes" gives false almost always, even if the user types exactly yes. The bug is insidious: in experiments with string literals, == seems to work correctly because of the pool.

equals has a null side too. null is the reference value that points to no object. A method cannot be called through a null reference:

String answer = null;
System.out.println("yes".equals(answer)); // false
System.out.println(answer + "!");          // null!
System.out.println(answer.equals("yes")); // exception

In the first line the method is called on the constant "yes"; since a constant is never null, the call is safe and returns false with a null argument. In the second line concatenation turns null into the text "null"; no exception occurs and null! is printed. The third line throws NullPointerException. Since Java 15 the message of this exception says by default which call failed and why:

Exception in thread "main" java.lang.NullPointerException:
    Cannot invoke "String.equals(Object)" because "answer" is null

The variable name in the message ("answer") is visible when the class file is compiled with debugging information. Development environments add this information by default. In a program compiled with only javac on the command line, the ordinal number of the local variable is written instead of the name:

Exception in thread "main" java.lang.NullPointerException:
    Cannot invoke "String.equals(Object)" because "<local1>" is null

When compiled with javac -g, the message shows the name "answer" again. Both messages describe the same error: equals was called on a variable that is null. The safe form is to put the constant first: "yes".equals(answer).

3.4.5.4Comparison methods

Besides equals, strings have a few more comparison methods. Table 3.4.9 lists them together with the type they return.

Table 3.4.9: String comparison methods.
MethodReturnsExplanation
equals(str)booleanIs the content exactly the same?
equalsIgnoreCase(str)booleanIs it the same when the difference between uppercase and lowercase is ignored?
startsWith(str)booleanDoes the string start with the given text?
endsWith(str)booleanDoes the string end with the given text?
contains(str)booleanDoes the given text occur inside the string?
isEmpty() / isBlank()booleanIs the length 0? / Does it consist only of whitespace? (isBlank: Java 11+)
compareTo(str)intDictionary order: negative (comes first), 0 (equal), positive (comes after).
compareToIgnoreCase(str)intcompareTo that ignores letter case.

Methods whose name does not contain IgnoreCase are case-sensitive. equals and equalsIgnoreCase do not throw an exception when given a null argument; they return false. The example in the slides tries these methods on the string "Giresun Üni."; the results in the comments are the real output of the program:

String s = "Giresun Üni.";
System.out.println(s.startsWith("Gir"));                // true
System.out.println(s.startsWith("Gır"));                // false
System.out.println(s.endsWith("Üni."));                 // true
System.out.println(s.endsWith("Üni"));                  // false
System.out.println(s.equalsIgnoreCase("Giresun Üni.")); // true
System.out.println(s.equalsIgnoreCase("Gıresun üni.")); // true
System.out.println(s.equalsIgnoreCase("GIresun Uni.")); // false
System.out.println(s.contains("Üni"));                  // true

Some of the results are surprising at first sight:

  • startsWith("Gır") is false. ı and i are separate characters; their Unicode codes are 305 and 105.
  • endsWith("Üni") is false, because the string ends with a period. The last character is '.'.
  • equalsIgnoreCase("Gıresun üni.") is true. When comparing characters, the method converts both sides to uppercase. The uppercase forms of ı and i are the same, I; so the two strings are treated as equal. equalsIgnoreCase does not look at the locale; it gives the same result on every machine.
  • equalsIgnoreCase("GIresun Uni.") is false. U and Ü are separate letters, and no case conversion makes them equal.
Giresun·Üni.startsWith("Gir")endsWith("Üni.")contains("Üni")
Figure 3.4.10: The regions matched by the methods startsWith, contains and endsWith.

Comparisons with the empty string are also worth knowing. Every string starts with the empty string and contains it: s.startsWith("") and s.contains("") are always true. s.indexOf("") returns 0.

3.4.5.5compareTo and dictionary order

Definition 3.4.11

a.compareTo(b) compares two strings in lexicographic order. It returns a negative int if a comes first, 0 if they are equal, and a positive one if it comes after. The comparison starts at the beginning and ends at the first differing character; the result is the difference of the Unicode codes of these two characters. If there is no differing character and one is a prefix of the other, the result is the difference of the lengths.

The example in the slides contains all the cases of the rule:

System.out.println("egg".compareTo("apple"));
System.out.println("apple".compareTo("egg"));
System.out.println("egg".compareTo("egg"));
System.out.println("Egg".compareTo("egg"));
System.out.println("Egg".compareToIgnoreCase("egg"));
System.out.println("do".compareTo("door"));
System.out.println("çay".compareTo("dut"));
4
-4
0
-32
0
-2
131

Let us read the lines according to the rule:

  • "egg".compareTo("apple"): the first characters differ. 'e' − 'a' = 101 − 97 = 4. Positive: “egg” comes after “apple”.
  • "apple".compareTo("egg"): the same characters in reverse order, −4. When the two are swapped, the sign changes.
  • Equal strings give 0.
  • "Egg".compareTo("egg"): 'E' − 'e' = 69 − 101 = −32. In Unicode, uppercase letters come before lowercase letters.
  • compareToIgnoreCase ignores letter case and gives 0.
  • "do".compareTo("door"): the first two characters are the same and "do" ends. One is a prefix of the other; the result is the difference of the lengths: 2 − 4 = −2.
  • "çay".compareTo("dut"): the code of 'ç' is 231 and the code of 'd' is 100. 231 − 100 = 131. A positive result means that “çay” comes after “dut”.

The last line shows an important limit: compareTo does not know the Turkish alphabet order. In Turkish, ç lies between c and d. But in Unicode the codes of the letters specific to Turkish are larger than those of the Latin letters: ç is 231, ı 305, ş 351, ü 252, while z is 122. In a list of Turkish words sorted in Unicode order, words that start with ç, ı or ş fall after z. For correct Turkish sorting, java.text.Collator is used:

import java.text.Collator;
import java.util.Arrays;
import java.util.Locale;

String[] m = {"zeytin", "çilek", "Elma", "armut", "ıhlamur", "incir"};
String[] m2 = m.clone();
Arrays.sort(m);                       // Unicode order
System.out.println(Arrays.toString(m));
Collator tr = Collator.getInstance(Locale.forLanguageTag("tr-TR"));
Arrays.sort(m2, tr);                  // Turkish alphabet order
System.out.println(Arrays.toString(m2));
[Elma, armut, incir, zeytin, çilek, ıhlamur]
[armut, çilek, Elma, ıhlamur, incir, zeytin]

Arrays.sort sorts strings with compareTo. As a result “Elma”, which starts with a capital letter, falls at the very front, and “çilek” and “ıhlamur” fall at the very end. The Turkish Collator, on the other hand, applies the alphabet order and puts the difference between uppercase and lowercase in the background when sorting. For lists to be shown to the user, the second way is chosen.

The trace slide in the slides shows the steps of compareTo on three pairs of strings:

String a = "case", b = "cave";
int r1 = a.compareTo(b);
int r2 = "car".compareTo("cargo");
int r3 = "Zeki".compareTo("ali");
System.out.println(r1 + " " + r2 + " " + r3);
-3 -2 -7
Table 3.4.10: compareTo trace. k is the index being compared.
PairkCharacters (codes)Case
"case", "cave"0'm' (109), 'm' (109)equal, continue
1'a' (97), 'a' (97)equal, continue
2's' (115), 'v' (118)different: 115 − 118 = −3
"car", "cargo"0–2all equal; "car" endsprefix: 3 − 5 = −2
"Zeki", "ali"0'Z' (90), 'a' (97)different: 90 − 97 = −7
"case"mas115a"cave"mav118i= -3
Figure 3.4.11: "case" and "cave" differ at index 2; the result is the difference of the codes, 115 − 118 = −3.

The third pair shows how far the uppercase rule goes: even Z comes before a. The size of the result usually carries no meaning; what matters is its sign. That is why the comparison is written if (a.compareTo(b) < 0) and not == -1. The operators < and > do not work with strings; the compiler gives a “bad operand types” error:

Compare.java:4: error: bad operand types for binary operator '<'
        if (a < b) System.out.println(a);
              ^
  first type:  String
  second type: String

3.4.6Formatted output

println writes a value as it is. When a grade sheet, an invoice or a table of measurements is printed, this is not enough. Columns must be aligned and floating-point numbers written with a certain number of digits. For this job Java offers the printf method and String.format, which uses the same rules.

3.4.6.1printf and format specifiers

Definition 3.4.12

System.out.printf(format, arguments…) takes a format string followed by any number of arguments. The format string contains format specifiers placed among plain text. Each specifier starts with % and ends with a type letter; the optional part in between gives the flag, the width and the precision. The arguments take the place of the specifiers in order.

The general form of a specifier is %[flag][width][.precision]type (Figure 3.4.12). In the specifier %-8.2f, the - flag left-aligns, 8 is the width, .2 is the precision and f is the type.

%start-left-align8width.2precisionftype
Figure 3.4.12: The parts of a format specifier: start (%), flag, width, precision and type.

Table 3.4.11 gives the most frequently used type letters. The decimal separator depends on the locale. A comma is used with the Turkish locale and a point with Locale.US.

Table 3.4.11: Basic format specifiers (outputs with the tr-TR locale).
SpecifierTypeExample → output
%dInteger (byte, short, int, long)42 → 42
%fFloating-point (float, double)%.1f: 3.14159 → 3,1
%sString (every value is converted to text)%5s: "ab" → ␣␣␣ab
%cCharacter'Z' → Z
%bBooleantrue → true
%nLine break—

printf does not move to the next line by itself. For a line break, \n or %n is added at the end of the format string. %n uses the line-break character of the operating system; on Windows it writes the two characters \r\n, on Linux and macOS \n. That is why %n is preferred in portable code.

The width is the minimum number of characters the value will occupy. If the value is shorter, it is padded with spaces: %Wd right-aligns and %-Wd left-aligns. If the value is longer than the width, it is not cut; the field grows. The precision is the number of digits after the decimal point for floating-point numbers, and the last digit is rounded: %.2f writes two digits. %8.2f sets aside a field of 8 characters in total, including the two decimal digits.

3.4.6.2Width and precision

The example in the slides writes the same three values in four different formats:

int i = 3;
float f = -17;
String s = "java";

System.out.printf("x: %d y: %f s: %s\n", i, f, s);
System.out.printf("x: %4d y: %5.2f s: %6s\n", i, f, s);
System.out.printf("x: %-4d y: %-7.2f s: %-6s\n", i, f, s);
System.out.printf("x: %-4d y: %-6.3f s: %-6s\n", i, f, s);
x: 3 y: -17,000000 s: java
x:    3 y: -17,00 s:   java
x: 3    y: -17,00  s: java··
x: 3    y: -17,000 s: java··

The output was obtained with the Turkish locale. The spaces at the end of the lines are shown with · so that they are visible. Two of the variables need an explanation: f is a float, and when the integer -17 is assigned to it, it becomes -17.0. If no precision is given to %f, 6 decimal digits are written. Let us examine the lines in order:

  1. No width is given. Each value takes as much room as its own length: 3, -17,000000, java.
  2. %4d right-aligns 3 in a field of four characters: three spaces and 3. %5.2f writes -17,00 with two decimals; this is 6 characters and does not fit in a width of 5, so the field grows. %6s puts two spaces to the left of the four-letter java.
  3. The minus flag left-aligns; spaces are added to the right of the value. %-4d → 3···, %-7.2f → -17,00·, %-6s → java··.
  4. %-6.3f writes -17,000 with three decimals. The value is 7 characters long and longer than the width of 6; no padding is done.

Figure 3.4.13 shows the second line character by character. The field occupied by each specifier is marked at the bottom.

x:␣␣␣␣3␣y:␣-17,00␣s:␣␣␣java%4d (4)%5.2f (6)%6s (6)
Figure 3.4.13: The output of "x: %4d y: %5.2f s: %6s" character by character. %4d occupies 4, %5.2f 6 (a field that grows because the value does not fit), and %6s 6 characters.

Width is most useful when printing tables. When the same specifiers are used on every row, the columns line up neatly one under the other. Text columns are usually left-aligned (%-10s) and number columns right-aligned (%6d, %8.2f). That way the units digits of the numbers fall one under another.

Example 3.4.3

Let us find, character by character, the output of the following line with the US English locale:

String name = "Ali";
double grade1 = 72.456;
System.out.printf("[%-5s][%3d][%7.2f]%n", name, 7, grade1);

%-5s: "Ali" has three letters, is left-aligned in a field of five characters and gets two spaces on its right: Ali··. %3d: 7 has one digit and gets two spaces on its left: ··7. %7.2f: 72.456 is rounded to two decimals and becomes 72.46. This text is 5 characters; to fill the field of seven characters, two spaces are added at the start: ··72.46. The result:

[Ali  ][  7][  72.46]

The rounding rule is also worth knowing. printf looks at the decimal representation of the number and rounds halves away from zero (HALF_UP). Unlike Math.round, it also moves away from zero for negative halves:

System.out.printf("[%.2f][%.2f][%.0f][%.0f][%.0f]%n", 2.345, 2.355, 0.5, 1.5, -2.5);
System.out.printf(Locale.US, "%,.2f %08.3f %+d %X%n", 1234567.891, 3.14159, 5, 255);
[2,35][2,36][1][2][-3]
1,234,567.89 0003.142 +5 FF

2.345 and 2.355 are rounded up as expected. 0.5 → 1, 1.5 → 2 and −2.5 → −3. The flags in the second line are explained in the next subsection.

3.4.6.3Other formats and String.format

System.out.printf("|%5s|%-5s|%05d|%.1f|%n", "ab", "ab", 42, 3.14159);
System.out.printf("%c %b %e %x %%%n", 'Z', true, 1234.5, 255);
String msg = String.format("%s: %d points", "Ayşe", 85);
System.out.println(msg);
System.out.printf("%,d%n", 1234567);
System.out.printf(Locale.US, "%.2f%n", 2.5);       // import java.util.Locale;
System.out.println("%s = %d".formatted("x", 7));   // Java 15+
|   ab|ab   |00042|3,1|
Z true 1,234500e+03 ff %
Ayşe: 85 points
1.234.567
2.50
x = 7

The new elements in this example are the following:

  • %05d: the 0 flag fills the field with zeros instead of spaces: 00042. It is used for fixed-length numbers such as invoice and student numbers.
  • %e is scientific notation: 1234.5 = 1.2345 × 103, in the output 1,234500e+03. %x writes in hexadecimal: 255 → ff; %X for uppercase. %% writes the percent sign itself.
  • String.format uses the same rules but does not write to the screen; it returns the formatted text as a String. The result can be stored in a variable, written to a file or appended to another text.
  • %,d adds a thousands separator. With the Turkish locale the separator is a point: 1.234.567. With the US locale it is a comma.
  • The first argument of printf can be a Locale. When Locale.US is given, the decimal separator becomes a point: 2.50. Data that another program will read (such as a CSV file) is written this way.
  • The formatted method that came with Java 15 is called on the format string: "%s = %d".formatted("x", 7) and String.format("%s = %d", "x", 7) give the same result.

For the compiler the format string is ordinary text. If a specifier and the type of its argument do not match, the error appears not at compile time but at run time. The call printf("%d", 3.5) gets a double instead of the integer that %d expects and throws an exception:

Exception in thread "main" java.util.IllegalFormatConversionException:
    d != java.lang.Double

The message means “the specifier d cannot be used with Double”. printf does not convert; it does not cut the number and write 3. The right way is to use %f or %.0f. If there are more specifiers than arguments, MissingFormatArgumentException is thrown. %s, on the other hand, works with every type, because every value can be converted to text.

3.4.7Applications

When the tools of the earlier sections, that is, indexing, loops, comparison and concatenation, are used together, real problems get solved. This section treats in detail the two applications in the slides and the small methods in the exercise slides.

3.4.7.1Palindrome check

Definition 3.4.13

A palindrome is a text that reads the same backward as forward: “kayak”, “level”, “noon”. In sentences, spaces and punctuation are ignored.

The most direct way to tell whether a text is a palindrome is to reverse the text and compare it with the original:

String text = "Kayak";
text = text.toLowerCase();
String rev = "";
for (int i = text.length() - 1; i >= 0; i--) {
  rev += text.charAt(i);
}
System.out.println(rev);
System.out.println(text.equals(rev));
kayak
true

The code works in three steps. First the text is converted to lowercase; if it were not, K and k would count as different. Because toLowerCase() returns a new string, the result is assigned to text again. In the second step an empty rev string is prepared and the loop goes down from the last index to 0. On each pass the character at that index is appended to the end of rev. In the third step the two strings are compared with equals. Table 3.4.12 gives the passes of the loop.

Table 3.4.12: The reversing loop for text = "kayak".
ii >= 0charAt(i)rev (at the end of the pass)
4true'k'"k"
3true'a'"ka"
2true'y'"kay"
1true'a'"kaya"
0true'k'"kayak"
−1false—the loop ends
textk0a1y2a3k4revkayak
Figure 3.4.14: text and rev when the loop ends. The contents are the same; equals returns true.

The comparison must be done with equals. rev is a new object built by concatenation at run time; text == rev would always give false. The line rev += … in the loop produces a new string on every pass. For short texts this does not matter, but the same job is done both briefly and efficiently with new StringBuilder(text).reverse().toString().

For sentences, the characters that are not letters are first deleted. The call text.replaceAll("[^\\p{L}]", "") uses a regular expression: \p{L} stands for every letter in Unicode and [^…] for “every character other than these”. Only the letters remain. When the Turkish sentence “Ey Edip Adana'da pide ye” is cleaned and lowercased, it becomes "eyedipadanadapideye", and this is a palindrome.

The reversing method creates a copy of the text. The same check can be done without using memory, with two indices: one starts from the front, the other from the end, and they compare characters until they meet in the middle. As soon as an inequality is found the result is false; there is no need to look at the remaining characters. The cost of both methods is proportional to the length of the text.

3.4.7.2Word frequency

Counting how many times each word occurs in a text is one of the most basic problems of text processing. The solution in the slides works only with arrays and two nested loops:

String text = "One two one six TWO one";
String[] words = text.toLowerCase().split(" ");
boolean[] counted = new boolean[words.length];
for (int i = 0; i < words.length; i++) {
  if (counted[i]) {
    continue; // this word was already counted
  }
  int freq = 1;
  for (int j = i + 1; j < words.length; j++) {
    if (words[i].equals(words[j])) {
      freq++;
      counted[j] = true;
    }
  }
  System.out.println(words[i] + ": " + freq);
}
one: 3
two: 2
six: 1

The code follows these steps:

  • text.toLowerCase().split(" ") first lowercases the text and then splits it at the spaces. Thanks to the lowercasing, “One/one” and “TWO/two” count as the same word.
  • The counted array keeps a flag for each word. When a boolean array is created, all the elements are false.
  • The outer loop looks at each word once. If the flag of the word is true, that word has been counted before; continue skips the rest of the pass.
  • The inner loop scans only the words to the right. For each matching word the counter increases and the flag of the match is set to true. This way the same word is not reported a second time.

The words are compared with equals. The pieces that split produces are separate objects created at run time. Had == been used, no match would have been found and the frequency of every word would have come out as 1. This was verified by running: with == the word “one” is counted only once.

The trace slide in the slides runs the same code on the text "apple Pear apple plum PEAR":

String text = "apple Pear apple plum PEAR";
String[] k = text.toLowerCase().split(" ");
boolean[] counted = new boolean[k.length];
for (int i = 0; i < k.length; i++) {
  if (counted[i]) continue;
  int freq = 1;
  for (int j = i + 1; j < k.length; j++) {
    if (k[i].equals(k[j])) {
      freq++;
      counted[j] = true;
    }
  }
  System.out.println(k[i] + ": " + freq);
}
apple: 2
pear: 2
plum: 1
Table 3.4.13: Trace of the word frequency. k = ["apple", "pear", "apple", "plum", "pear"]; the flags are at the end of each outer pass.
ik[i]Matching jfreqcountedOutput
0egg22F F T F Fapple: 2
1apple42F F T F Tpear: 2
2egg——F F T F Tflag set, continue
3plumnone1F F T F Tplum: 1
4apple——F F T F Tflag set, continue
kegg0falseapple1falseegg2trueplum3falseapple4falsecounted
Figure 3.4.15: The word array and the flags at the end of the pass i = 0. The “apple” at index 2 has been marked as counted.

The cost of the algorithm grows with the square of the number of words. For n words the inner loop makes (n − 1) + (n − 2) + … + 1 = n(n − 1)/2 comparisons in the worst case. For a text of a few sentences this is very little. If all the words of a book are to be counted, a collection that keeps key-value pairs (HashMap) gives a much faster result.

3.4.7.3Small string methods

The exercise and example-problem slides of the presentation contain a few short methods that combine string methods. These methods show common patterns of indexing and looping.

Reversing. The reverse method moves the loop in the palindrome example into a method:

static String reverse(String s) {
  String rev = "";
  for (int i = s.length() - 1; i >= 0; i--) {
    rev += s.charAt(i);
  }
  return rev;
}

The call reverse("Giresun") returns nuseriG. The capital G has moved to the end; the method does not touch letter case.

Counting characters. The count method finds how many times a character occurs:

static int count(String s, char target) {
  int count = 0;
  for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == target) {
      count++;
    }
  }
  return count;
}

The comparison s.charAt(i) == target is correct, because both sides are char and char is a primitive type. Here == compares values, not references. count("Karadeniz", 'a') returns 2: K is an uppercase letter and does not match 'a'; the only matches are the as at indices 1 and 3.

Capitalizing the first letter. capitalize makes the first letter uppercase and the rest lowercase:

static String capitalize(String word) {
  return word.substring(0, 1).toUpperCase()
       + word.substring(1).toLowerCase();
}

The method handles the two parts separately and joins them: substring(0, 1) is the first letter and substring(1) is the rest. capitalize("jAVA") → Java. With the Turkish locale, capitalize("istanbul") → İstanbul and capitalize("ılgaz") → Ilgaz. If it is called with the empty string, substring(0, 1) asks for an invalid range and a StringIndexOutOfBoundsException is thrown. A robust version first checks if (word.isEmpty()) return word;.

Counting vowels. indexOf can be used to tell whether a character is in a set:

String word = "Ordu";
String vowels = "aeıioöuüAEIİOÖUÜ";
int count = 0;
for (int i = 0; i < word.length(); i++) {
  char c = word.charAt(i);
  if (vowels.indexOf(c) != -1) {
    count++;
  }
}
System.out.println("Vowels: " + count);
Vowels: 2

The string vowels contains the eight vowels of Turkish in their uppercase and lowercase forms. For each character vowels.indexOf(c) is called; if the result is not −1, the character is a vowel. In "Ordu", O and u are vowels: Vowels: 2. This pattern is both shorter and more readable than an if chain with eight branches.

Number of words. If there is a single space between the words, the number of words is found in one line: sentence.split(" ").length. For "Java and object oriented programming" the result is 5. If there can be several spaces between the words, sentence.trim().split(" +").length is written.

Example 3.4.4

The first example problem in the slides tests immutability, substring, indexOf and the order of concatenation together:

String s = "Karadeniz";
s.toUpperCase();
String t = s.substring(2, 5);
System.out.println(t + " " + t.length());
System.out.println(s.indexOf("de"));
System.out.println(s.indexOf("x"));
System.out.println(1 + 2 + "3" + 4 + 5);
rad 3
4
-1
3345

Because the result of s.toUpperCase() is not assigned, s does not change. The indices of "Karadeniz" are K0 a1 r2 a3 d4 e5 n6 i7 z8. substring(2, 5) takes indices 2, 3, 4: "rad", length 3. "de" starts at index 4. "x" is not in the string, −1. The last line is computed from left to right: 1 + 2 = 3 (two numbers), 3 + "3" = "33", then "334" and "3345".

The second problem tests the pool:

String a = "java";
String b = "ja" + "va";
String c = new String("java");
String d = c;
System.out.println(a == b);
System.out.println(a == c);
System.out.println(c == d);
System.out.println(a.equals(c));
true
false
true
true

"ja" + "va" is a constant computed at compile time and points to the same object as a in the pool: a == b is true. c is a separate object created with new: a == c is false. d = c copies the reference; both are the same object: true. Because the contents are the same, a.equals(c) is true.

The third problem extracts initials and parts of an e-mail address:

public static String initials(String name, String surname) {
  return name.charAt(0) + "." + surname.charAt(0) + ".";
}
System.out.println(initials("Sercan", "Külcü"));
String e = "student@giresun.edu.tr";
int at = e.indexOf('@');
System.out.println(e.substring(0, at));
System.out.println(e.substring(at + 1));
S.K.
student
giresun.edu.tr

In the expression name.charAt(0) + ".", the right side is a string, so concatenation is done: "S.". If two chars had been added directly, the result would have been a number; 'S' + '.' gives 83 + 46 = 129. The e-mail part is the same as the example solved earlier.

3.4.8Common mistakes

The compiler catches some of the mistakes with strings; if its message is read, they are easy to fix. Others compile and then give wrong results or throw exceptions when run. Table 3.4.14 summarizes the first group and Table 3.4.15 the second. The messages were taken from the javac of JDK 21.

Table 3.4.14: String mistakes caught by the compiler.
MistakeCompiler messageFix
String s = 'Hello';unclosed character literalSingle quotes are only for a single character; a string is written with double quotes.
char c = "a";incompatible types: String cannot be converted to charchar c = 'a'; or "a".charAt(0).
s.lengthcannot find symbol / symbol: variable lengthIn a string length() is a method. For an array it is the opposite: d.length.
string s = …;cannot find symbol / symbol: class stringThe class name is String; Java is case-sensitive.
int n = "42";incompatible types: String cannot be converted to intInteger.parseInt("42").
s.charAt(0) = 'j';unexpected type / required: variableA string is immutable; use a new string or StringBuilder.setCharAt.
s[0]array required, but String founds.charAt(0).
if (a < b) (strings)bad operand types for binary operator '<'a.compareTo(b) < 0.

For the error in the first line javac actually gives three messages: unclosed character literal twice and not a statement once. The compiler takes the single quote to be the start of a character literal, sees that the quote is not closed, and cannot make sense of what follows. In such chained messages the first message shows the real cause:

Quote.java:3: error: unclosed character literal
        String s = 'Hello';
                   ^
Table 3.4.15: String code that compiles but runs wrongly.
MistakeSymptomFix
Comparing the content with ==The condition is false even though the user input is right."yes".equals(input)
Forgetting to assign the results does not change after s.toUpperCase();.s = s.toUpperCase();
Thinking the last index is length()StringIndexOutOfBoundsException: Index 4 out of bounds for length 4s.charAt(s.length() - 1); i < s.length() in loops
nextLine after nextIntThe line is read as empty and the question is skipped.Put a keyboard.nextLine(); in between
Calling a method on a null stringNullPointerException: Cannot invoke "String.equals(Object)"Put the constant first: "yes".equals(answer)
Thinking the end of substring is includeds.substring(5, 12) gives 7 characters, not 8.Length = end − start.
Addition without parentheses"Total: " + x + y → Total: 105"Total: " + (x + y)
Case conversion with the default locale"TITLE".toLowerCase() gives tıtle with the Turkish locale.toLowerCase(Locale.ROOT) or equalsIgnoreCase
A wrong specifier in printfIllegalFormatConversionException%d for integers, %f for floating-point numbers.

What the mistakes in the second table have in common is that the compiler cannot see them. == and equals are both valid Java. A method call whose result is not assigned is a valid statement too. The best protection against these mistakes is to try the program with different inputs and compare the output with the expected value. The empty string, a one-character string, Turkish letters and leading and trailing spaces in particular make good test inputs.

3.4.9Summary

  • String is an immutable object that stores a sequence of characters. It is created with a string literal ("…") or with new; since it is in the java.lang package it needs no import.
  • Concatenation: + is evaluated from left to right. If one of the operands is a string, concatenation is done; if both are numbers, addition. char is a number: 'a' + 'b' = 195. Parentheses are used to add numbers.
  • The index runs from 0 to length() - 1. charAt(i) returns a char. An index that goes outside throws StringIndexOutOfBoundsException. In a string length() is a method, in an array length is a field.
  • Methods: indexOf (−1 if not found), substring(a, b) (b excluded, length b − a), toUpperCase, replace, trim, split, join; all return a new value and the result must be assigned.
  • Locale: case conversion without a parameter depends on the setting of the machine. With the Turkish locale i ↔ İ, ı ↔ I. Locale.ROOT is used for texts inside the program.
  • StringBuilder: a mutable buffer. Concatenation with += in a loop does O(n²) work, with append O(n). When the capacity is full it roughly doubles (20 → 42).
  • Scanner: next() reads a word and nextLine() the rest of the line. After nextInt() the ⏎ stays in the buffer; a nextLine() that follows returns the empty string.
  • == / equals: == asks whether it is the same object, equals asks whether the content is the same. The content of strings is always compared with equals; against null the constant is put first.
  • String pool: string literals with the same content share one object. new and run-time concatenation produce a new object; intern() gives the pool counterpart.
  • compareTo: returns the code difference of the first differing character, or the length difference in the case of a prefix. It uses Unicode order; for Turkish alphabet order Collator is needed.
  • printf: %d, %f, %s, %c, %b, %n. %Wd right-aligns and %-Wd left-aligns; %.2f writes two decimal digits. A value that does not fit enlarges the field. Separators depend on the locale.

3.4.10Key terms

  • string
  • string literal
  • string concatenation
  • character (char)
  • Unicode
  • index
  • indexing
  • immutable
  • reference
  • heap
  • garbage collector
  • locale
  • buffer
  • string pool
  • null reference
  • format specifier
  • compile time / run time
  • runtime error
  • exception
  • literal
  • reference type

3.4.11Test Yourself

  1. What does System.out.println(2 + 3 + "x" + 2 + 3); print? How is the expression changed so that the sum of the last two numbers is printed?

    Answer

    It prints 5x23. The two numbers on the left are added (5) before a string is met. Every + after "x" is concatenation. For the sum at the end, parentheses are needed: 2 + 3 + "x" + (2 + 3) → 5x5.

  2. For String s = "Karadeniz Teknik";, what are s.indexOf(' '), s.substring(s.indexOf(' ') + 1) and s.lastIndexOf('e')?

    Answer

    “Karadeniz” has nine letters; the space is at index 9. substring(10) gives what follows the space: Teknik. T is at index 10, e at index 11, and there is no other e after it: lastIndexOf('e') = 11.

  3. After the lines StringBuilder sb = new StringBuilder("abc"); sb.append("de").insert(2, "X").reverse();, what are the content and the length of sb? How many objects would be created if the same operations were done with String?

    Answer

    "abc" → append → "abcde" → insert(2, "X") → "abXcde" → reverse → edcXba, length 6. All the operations are done on the same object. With String each step would produce a new string: three new objects besides the initial string.

  4. What do "Ankara".compareTo("Antalya") and "abc".compareTo("ab") return? If these strings are put in alphabetical order, which comes first?

    Answer

    In the first pair the strings differ at index 2, 'k' (107) versus 't' (116): 107 − 116 = −9. Because it is negative, “Ankara” comes first. In the second pair "ab" is a prefix of "abc"; the result is the difference of the lengths: 3 − 2 = 1. “ab” comes first.

  5. After the lines String x = "Ada"; String y = "A" + "da"; String z = new String("Ada"); String w = z.intern();, what do x == y, x == z, x == w and z.equals(y) give?

    Answer

    true false true true. "A" + "da" becomes the constant "Ada" at compile time and points to the object in the pool. z is a separate object outside the pool. intern() returns its counterpart in the pool, that is, the object of x. Because the contents are the same, equals gives true.

  6. What is the output of System.out.printf("[%6.1f][%-4s][%3d]%n", 9.96, "ok", 12345); on a computer set to Turkish?

    Answer

    [ 10,0][ok ][12345]. When 9.96 is rounded to one decimal it becomes 10.0; this is 4 characters and two spaces are added at the start. "ok" is left-aligned and two spaces come to its right. 12345 has five digits and does not fit in a width of 3; the field grows and the number is not cut.

  7. At the keyboard, first ␣␣42␣␣Ayşe Yılmaz⏎ and then Son⏎ are typed. After the lines int n = k.nextInt(); String r = k.nextLine(); String t = k.next();, what are n, r and t?

    Answer

    nextInt() skips the leading spaces and reads 42. nextLine() does not skip spaces; it takes the rest of the line: r = " Ayşe Yılmaz" (two spaces at the start). Because the ⏎ has been consumed, next() reads the word on the second line: t = "Son".

  8. What does String u = "Banana"; u.replace('a', 'e'); u.concat("!"); System.out.println(u); print? How is the code fixed if the programmer wants to see Benene!?

    Answer

    It prints Banana. Both methods return a new string, but the results are lost because they are not assigned. The fixed form: u = u.replace('a', 'e').concat("!"); or two separate assignments.

  9. How many elements does the array returned by "a-b--c".split("-") have? What does "KIRMIZI".toLowerCase().equals("kirmizi") give on a computer set to Turkish?

    Answer

    An empty piece is produced between two consecutive hyphens: ["a", "b", "", "c"], 4 elements. The second expression gives false: when I is lowercased with Turkish rules it becomes ı and the result is "kırmızı". toLowerCase(Locale.ROOT) or equalsIgnoreCase gives true.

3.4.12Further reading

  • Oracle, The Java Tutorials, the section “Numbers and Strings”: the official tutorial that explains String, StringBuilder and formatted number output with short examples.
  • Oracle, Java SE 21 API Documentation, the class java.util.Formatter: the complete list of all the flags, the width and precision rules and the type letters that can be used in printf.
  • J. Gosling et al., The Java Language Specification, Java SE 21, §3.10.5 and §15.18.1: define precisely the sharing of string literals in the pool and the rules for concatenation with +.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, Chapter 3.6: treats strings, StringBuilder and the Java counterpart of Unicode from the point of view of an experienced programmer.

3.4.13References

  1. Oracle, The Java Tutorials: “Strings”, “Comparing Strings and Portions of Strings”, “The StringBuilder Class”, “Formatting Numeric Print Output”.
  2. Oracle, Java SE 21 API Documentation: java.lang.String, java.lang.StringBuilder, java.util.Scanner, java.util.Formatter, java.util.Locale.
  3. J. Gosling vd., The Java Language Specification, Java SE 21 Edition (§3.10.5 String Literals, §15.18.1 String Concatenation Operator +).
  4. P. Deitel, H. Deitel, Java: How to Program, 11th ed., Pearson, 2017 (Chapter 14: Strings, Characters and Regular Expressions).
  5. C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., 2022 (Chapter 3.6: Strings).
  6. A. B. Downey, C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 6: Loops and Strings).

Related pages: Chapter 3.4 slides · Study questions · String Pool · Glossary · © Sercan Külcü. All rights reserved.