Computer Fundamentals and Introduction to Programming · Lecture Notes

Chapter 11: Strings

Most of the data programs process is text: student names, email addresses, sentences typed at the keyboard, reports printed to the screen. In Java, text is represented by objects of the String class. These notes explain how strings are held in memory, why they cannot be changed, and their most frequently used methods. Reaching characters by index, taking substrings, searching, splitting and replacing are treated one by one. Comparison of strings follows: the difference between == and equals, lexicographic order with compareTo, and the traps caused by Turkish letters. Reading text from the keyboard, efficient concatenation with StringBuilder and formatted output with printf are also among the topics. The applications in the last section (reversing, palindromes, counting vowels and words, letter frequency, the Caesar cipher) bring all these tools together. Every program was compiled and run with JDK 21; the outputs given are the real outputs of the programs.

Learning outcomes

Representation
Explain the difference between String and char, that a string variable holds a reference and that strings are immutable; tell the empty string from null.
Processing
Reach characters with an index and charAt; use methods such as length, indexOf, substring, split and replace with correct bounds; scan a string with a loop.
Comparison
Tell content comparison (equals) from reference comparison (==); compute the result of compareTo; explain the effect of the locale on Turkish letters.
Input and output
Read words and lines with Scanner and trace the buffer behavior; concatenate efficiently with StringBuilder; produce formatted text with printf.

11.1What is a string?

Most of the programs written so far worked with numbers. A number is held in an int or double variable and goes into arithmetic operations. Text is a different structure: an ordered sequence of letters, digits, spaces and punctuation marks. This section introduces the two building blocks of text in Java, the types char and String.

11.1.1Characters and strings

Definition 11.1

A character is a single letter, digit, space or mark of text. In Java a character is held in a variable of type char and is written in single quotes: 'T', '7', ' '. A string is an ordered sequence of zero or more characters. In Java, strings are objects of the String class and are written in double quotes: "Tarkan", "7", "".

The kind of quote matters. 'T' is a single character and its type is char. "T" is a string of length 1 and its type is String. The two look the same on the screen but are different types for Java. This is why a string cannot be assigned to a char variable:

public class WrongType {
    public static void main(String[] args) {
        char c = "T";
        System.out.println(c);
    }
}
WrongType.java:3: error: incompatible types: String cannot be converted to char
        char c = "T";
                 ^
1 error

The message says that the type String cannot be converted to the type char. The correct form is char c = 'T';.

The String class is in the java.lang package. This package is added to every Java program automatically; the import line needed for Scanner is not needed for String. A piece of text written directly in the program, such as "Tarkan", is called a string literal.

11.1.2A string is an object

Primitive types such as char, int and double hold their values directly inside the variable. String, however, is not a primitive type; it is a class. A String variable holds not the text itself but the location in memory of the object that carries the text. This location information is called a reference. Figure 11.1 compares how the two types look in memory.

StackHeapname0T1a2r3k4a5nString object: a sequence of charactersc'T'char: the value is directly on the stack
Figure 11.1: Memory after the declarations String name = "Tarkan"; and char c = 'T';. The variable name holds an arrow (a reference) pointing to the six-character object on the heap. The variable c carries the value 'T' directly inside itself.

The names of the two memory regions in the figure appear in all the later drawings. The stack is the region where the local variables of methods are kept. The heap is the region where objects created with new, and strings, live. A String variable on the stack points to the object on the heap with an arrow. Several variables can point to the same object. This sharing is decisive when strings are compared.

Definition 11.2

An object is a piece of memory produced from a class, carrying its own data and methods. A reference is a value that shows where an object is in memory. In the declaration String s = "Ada";, the variable s is a reference; "Ada" is the object on the heap.

One consequence of being an object is methods. Operations belonging to a string are called with the dot: name.length() gives the length of the string and name.charAt(0) its first character. Primitive types have no methods; a notation such as c.length() does not compile.

11.1.3Creating strings, the empty string and null

A string variable can be given an initial value in four different ways:

String name = "Tarkan";
String empty = "";
String copy = new String(name);
String none = null;

The first line is the most common form: name points to the constant "Tarkan". The "" in the second line is the empty string, which contains no characters. The third line creates a new object with new and copies the contents of name into it. The null in the fourth line means that the variable points to no object at all. Figure 11.2 shows the state of the four variables in memory.

StackHeapString pool (constants)Tarkan""length 0Tarkannew: separatenameemptycopynonenull
Figure 11.2: Four string variables. name and empty point to constants in the string pool. copy points to a separate object created with new; even though its contents are the same, the object is different. none points to no object.

The string pool in the figure is a special region inside the heap where a single copy of each constant is kept. The rule here is short: a string created with a literal comes from the pool, while new always creates a new object. In practice there is almost never a need to write new String(...); the string literal is preferred.

The empty string and null are often confused. The empty string is a real object; its length is 0 and all its methods can be called. null is not an object; it is the state of a variable that says “I do not point to anything yet”. If a method is called through a null variable, the program stops with a NullPointerException. The program below prints the four variables and then calls none.length():

public class Creation {
    public static void main(String[] args) {
        String name = "Tarkan";
        String empty = "";
        String copy = new String(name);
        String none = null;
        char c = 'T';
        System.out.println(name + " " + name.length());
        System.out.println("[" + empty + "] " + empty.length());
        System.out.println(copy + " " + copy.length());
        System.out.println(none);
        System.out.println(c);
        System.out.println(none.length());
    }
}
Tarkan 6
[] 0
Tarkan 6
null
T
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "none" is null

In the output you can see that the empty string shows nothing between the square brackets and that its length is 0. System.out.println(none) does not cause an error; it prints null. The error occurs only when a method is called through null. The JDK 21 message also states the cause of the problem: because none is null, String.length() cannot be called.

Common mistake

Giving null to a string variable whose value is not known yet and then calling a method on it. If the variable will be filled in a loop or a condition, making its initial value "" is often safer. If null really means “no value”, a check s != null is made before the method call.

11.1.4Concatenation with +

Joining two strings end to end is called string concatenation. In Java the + operator is used for this. The same operator does addition on numbers. Which one happens is decided by the types of the operands: if at least one of the two operands is a String, + is concatenation; if both are numbers, it is addition.

public class Concatenation {
    public static void main(String[] args) {
        String num1 = "12";
        String num2 = "34";
        String total = num1 + num2;
        System.out.println(total);
        int a = 12, b = 34;
        System.out.println(a + b);
        System.out.println(num1 + 3 + 4);
        System.out.println(3 + 4 + num1);
        System.out.println(num1 + (3 + 4));
        System.out.println("Total: " + a + b);
        System.out.println("Total: " + (a + b));
        System.out.println("x" + null + 'c' + 2.5 + true);
        System.out.println("Merhaba".concat(" dünya"));
    }
}
1234
46
1234
712
127
Total: 1234
Total: 46
xnullc2.5true
Merhaba dünya

The program works line by line as follows. num1 + num2 concatenates two strings; even though the variable is named “total”, the result is "1234". a + b adds two ints: 46. The next two lines show the effect of the order of evaluation. + is evaluated from left to right:

  • num1 + 3 + 4: first "12" + 3 is computed. Because one operand is a string, 3 is converted to a string: "123". Then "123" + 4 = "1234".
  • 3 + 4 + num1: first 3 + 4 is computed. Both are numbers: 7. Then 7 + "12" = "712".
  • num1 + (3 + 4): the parentheses are computed first: 7. Then "12" + 7 = "127".

The line "Total: " + a + b falls into the same trap: because of the string on the left, both numbers are appended to the text one by one and “Total: 1234” is printed. To print the sum, parentheses are needed: "Total: " + (a + b). null, char, double and boolean values can also be added to a string; each is converted to its text form. The concat method also joins two strings, but it accepts only strings.

Example 11.1

With int x = 5, y = 2;, what are the values of the expressions "x+y=" + x + y and x + y + "=x+y"?

Solution. In the first expression the leftmost operand is a string. "x+y=" + 5 = "x+y=5", then "x+y=5" + 2 = "x+y=52". In the second expression the first two operands are numbers: 5 + 2 = 7. Then 7 + "=x+y" = "7=x+y". The same three operands give a different result when their order changes.

11.1.5A char is a number

Computers store characters as numbers. In the Unicode standard every character has a code number: 'a' is 97, 'b' is 98, 'A' is 65 and '0' is 48. In Java, char is really a 16-bit unsigned integer type. So a char can take part in arithmetic. The type of the result follows a rule: when a char is added to an integer, or two chars are added, the result is int.

public class CharArithmetic {
    public static void main(String[] args) {
        char k = 'a';
        System.out.println(k + 1);
        System.out.println((char) (k + 1));
        System.out.println("" + k + 1);
        System.out.println('a' + 'b');
        System.out.println("" + 'a' + 'b');
        k++;
        System.out.println(k);
    }
}
98
b
a1
195
ab
b

k + 1 is an int: 97 + 1 = 98. (char) (k + 1) converts this number back to a character: b. In the expression "" + k + 1, the empty string on the far left turns the whole expression into concatenation: first "a", then "a1". 'a' + 'b', however, is the sum of two numbers: 97 + 98 = 195. To print two characters side by side, "" is again put at the start. k++ increases the char variable in place and its type does not change: b.

That characters are numbers is useful in most string operations. The difference of two lowercase letters gives their distance in the alphabet: 'k' − 'a' = 107 − 97 = 10. Subtracting '0' from a digit character gives the numeric value of the digit: '7' − '0' = 55 − 48 = 7. The letter-frequency and Caesar cipher applications rest on these two ideas.

public class CharNumber {
    public static void main(String[] args) {
        System.out.println((int) 'a' + " " + (int) 'k' + " " + (int) 'v' + " " + (int) 'z' + " " + (int) 'A' + " " + (int) '0');
        System.out.println('k' - 'a');
        System.out.println((char) ('a' + 10));
        System.out.println((int) 'ç' + " " + ('ç' - 'a') + " " + (int) 'ı' + " " + (int) 'İ' + " " + (int) 'ş');
        System.out.println('7' - '0');
    }
}
97 107 118 122 65 48
10
k
231 134 305 304 351
7

The last lines also show the codes of Turkish letters: 'ç' is 231, 'ı' is 305, 'İ' is 304 and 'ş' is 351. These codes lie outside the range 97–122 of the English alphabet. Because 'ç' − 'a' = 134, there is no room for 'ç' in a 26-cell letter table running from 'a' to 'z'.

11.2Immutability

The most important property of strings is that their contents do not change after they are created. At first this property seems strange: when you write s = s + "!", it looks as if s has changed. In reality, what changes is not the object but the place the variable points to.

11.2.1A new object, the same old object

Definition 11.3

An object whose contents cannot be changed after it is created is called an immutable object. String is an immutable class: none of its methods changes the characters of the object. Every operation that “changes” a string (concatenation, converting to uppercase, taking a substring, replacing) produces a new String object and returns it. This property is called immutability.

Figure 11.3 shows the simplest example. After the line String s = "Merhaba";, s points to the seven-character object. The line s = s + "!"; does not add an exclamation mark to this object. First s + "!" is computed and a new eight-character object is created. Then the assignment moves the arrow of s to this new object. The old "Merhaba" object stays as it was.

StackHeapMerhabas StackHeapMerhabaunchangedMerhaba!news
Figure 11.3: The assignment s = s + "!";. Top: the state before the assignment, where s points to the “Merhaba” object. Bottom: the state after the assignment, where a new object “Merhaba!” has been created and the arrow has moved to it; the old object has not changed.

This can also be seen with a program. If a second variable (old) is kept pointing to the old object before the assignment, it becomes clear after the assignment that the two variables point to different objects:

public class Exclaim {
    public static void main(String[] args) {
        String s = "Merhaba";
        String old = s;
        s = s + "!";
        System.out.println(s);
        System.out.println(old);
        System.out.println(s == old);
    }
}
Merhaba!
Merhaba
false

old still points to “Merhaba”. The comparison s == old asks whether the two variables point to the same object, and it gives false: there are now two separate objects. Objects that no variable points to become unnecessary in time. In Java the garbage collector cleans up these objects automatically; the programmer does not have to give memory back by hand.

11.2.2Tracing the toUpperCase example step by step

The practical consequence of immutability is this: if the result of a string method is wanted, it must be assigned to a variable. The five lines below show this point.

String lang = "java";
lang.toUpperCase();
System.out.println(lang); // java
lang = lang.toUpperCase();
System.out.println(lang); // JAVA
java
JAVA

The second line calls lang.toUpperCase() but puts the returned value nowhere. The method does its job and produces a new "JAVA" object. But no variable points to this object; the result is lost. Because lang keeps pointing to the old object, the third line prints java. In the fourth line the result of the same call is assigned to lang; the arrow moves to the new object and the fifth line prints JAVA. Table 11.1 is the trace table of the five lines; Figure 11.4 shows the two critical moments.

Table 11.1: The trace table of the toUpperCase example. The “Objects on the heap” column gives the string objects in memory after that line.
LineWhat does lang point to?Objects on the heapOutput
1"java""java"
2"java""java", "JAVA" (nobody points to it)
3"java""java", "JAVA" (garbage)java
4"JAVA" (new object)"java", "JAVA"
5"JAVA""java", "JAVA"JAVA
StackHeapString pool (constants)javaJAVAnobody points to itlang StackHeapString pool (constants)javaJAVAlang
Figure 11.4: Top: the state after line 2, where toUpperCase() has produced a new “JAVA” object but no variable points to it. Bottom: the state after line 4, where the returned object has been assigned to lang and the arrow has moved to it. The “java” object is the same in both states.
Common mistake

Writing lines such as name.trim();, name.toUpperCase(); or name.replace('a', 'e'); on their own and thinking that name has changed. These lines compile and run, but the result is thrown away. The correct form is to assign the result again, as in name = name.trim();. Some development environments show a warning for calls whose returned value is not used.

There is also no way to change a single character of a string in place. For arrays you can write a[0] = 5;, but there is no corresponding operation for strings. charAt is for reading only; it cannot be assigned to:

public class SetCharAt {
    public static void main(String[] args) {
        String s = "java";
        s.charAt(0) = 'J';
        System.out.println(s);
    }
}
SetCharAt.java:4: error: unexpected type
        s.charAt(0) = 'J';
                ^
  required: variable
  found:    value
1 error

The message says that a variable was expected to the left of the equals sign but a value was found. s.charAt(0) produces a value; it is not a place in memory. To capitalize the first letter, a new string is built: s = Character.toUpperCase(s.charAt(0)) + s.substring(1); This line produces "Java".

11.2.3Why is immutability useful?

Producing a new object at every change may seem wasteful. Java's designers chose to pay this price for three gains:

  • Safe sharing. Several variables can point to the same string object. Because none of them can change the object, an operation done through one variable does not affect the others. The string pool is possible because of this: all the "Giresun" literals in the program share a single object.
  • Predictability. When a string is passed to a method, the method cannot corrupt it. The calling side is sure that the string is the same when it returns from the method.
  • Security. File names, network addresses and passwords are carried in strings. That a file name that has passed a check cannot be changed afterward is an important guarantee.

The price is that a large number of concatenations slows down. If s = s + x is written thousands of times in a loop, a new object is produced on every iteration and the old contents are copied. For this case Java offers a mutable helper class: StringBuilder.

11.3Indexing

The characters of a string are ordered, and each has a sequence number. This number is called the index. As with arrays, counting in strings starts at 0.

Definition 11.4

The characters of a string of length n are at indices 0, 1, …, n − 1. The first character is at index 0 and the last at index n − 1. Reaching a character by its index is called indexing. In Java, s.length() returns the length of the string, and s.charAt(i) returns the character at index i as a char value.

0G1i2r3e4s5u6nss.length() = 7s.charAt(0) → 'G's.charAt(6) → 'n'7✗
Figure 11.5: The indices of the string s = "Giresun". The seven characters are numbered 0 to 6. s.charAt(0) returns 'G' and s.charAt(6) returns 'n'. There is no cell number 7; s.charAt(7) is invalid.

For the string in Figure 11.5, the following program prints the length and the first and last characters. The index of the last character is found for any string with the expression s.length() - 1; this way the code works whatever the length.

public class Index {
    public static void main(String[] args) {
        String s = "Giresun";
        System.out.println(s.length());
        System.out.println(s.charAt(0));
        System.out.println(s.charAt(s.length() - 1));
        int[] arr = {4, 8, 15};
        System.out.println(arr.length + " " + s.length());
        System.out.println(s.charAt(7));
    }
}
7
G
n
3 7
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 7 out of bounds for length 7

The last line tries to reach the nonexistent character number 7. The compiler does not catch this error, because the index is usually computed while the program runs. The error shows up at run time as a StringIndexOutOfBoundsException. The message says that index 7 is outside the bounds of a string of length 7. An index like this is called an out-of-bounds index.

The difference between arr.length and s.length() in the program is also important. For arrays, length is a field and is written without parentheses. For strings, length() is a method and is called with parentheses. If the parentheses are forgotten, the program does not compile:

public class StringNotMethod {
    public static void main(String[] args) {
        String s = "Giresun";
        System.out.println(s.length);
    }
}
StringNotMethod.java:4: error: cannot find symbol
        System.out.println(s.length);
                            ^
  symbol:   variable length
  location: variable s of type String
1 error

The compiler says that it cannot find a variable named length in the type String. The word “symbol” in the message means a named program element such as a variable, a method or a class.

Common mistake

Trying to reach the last character with s.charAt(s.length()). If the length is n, the last index is n − 1; s.charAt(s.length()) is always out of bounds. The same mistake is seen in loops too: the last iteration of the loop for (int i = 0; i <= s.length(); i++) throws an exception at charAt. The correct condition is i < s.length().

11.4String methods

The String class has more than sixty methods. This section covers the ones most often needed in everyday programs. One rule holds for all of them: no method changes the original string. If a result is needed, the method returns it as a new value.

11.4.1length, indexOf, substring and contains

Four basic methods are used together in this program:

public class BasicMethods {
    public static void main(String[] args) {
        String s = "Java Programlama";
        int len = s.length();
        int pos = s.indexOf("Programlama");
        String sub = s.substring(5, 16);
        boolean has = s.contains("Java");
        System.out.println(sub + " " + pos);
        System.out.println(len + " " + has + " " + s.indexOf("java") + " " + s.indexOf('a') + " " + s.lastIndexOf('a'));
    }
}
Programlama 5
16 true -1 1 15

The last println line of the program is a check line added to the first six lines; its output is explained separately below. The first six lines work as follows:

  1. s points to the 16-character string "Java Programlama". The space in between is also a character and is at index 4.
  2. s.length() returns 16. The indices run from 0 to 15.
  3. s.indexOf("Programlama") returns the index of the first character of the text searched for. “P” is at index 5; pos becomes 5. If the text searched for did not occur at all, the result would be −1.
  4. s.substring(5, 16) gives the part that starts at index 5 and ends before index 16. The start is included and the end is excluded. The length of the part is 16 − 5 = 11: "Programlama".
  5. s.contains("Java") returns true if the text searched for occurs anywhere in the string.
  6. sub + " " + pos is concatenated and printed: Programlama 5.
Table 11.2: The trace table of the basic methods program. An empty cell shows that the variable has not been declared yet.
LinelenpossubhasOutput
1
216
3165
4165"Programlama"
5165"Programlama"true
6165"Programlama"trueProgramlama 5
0J1a2v3a4␣5P6r7o8g9r10a11m12l13a14m15a▲ pos
Figure 11.6: The sixteen cells of the string "Java Programlama". indexOf("Programlama") gives the index of “P”, the first character of the text searched for, that is, 5; the arrow points to this cell.

The check line added to the program shows three more details. s.indexOf("java") gives −1, because the search is case-sensitive: the string contains “Java”, not “java”. s.indexOf('a') gives 1; indexOf can also search for a single character and finds the place where it first occurs. s.lastIndexOf('a') searches from the end and finds the place where it last occurs, 15.

Example 11.2

For String t = "bilgisayar";, what are the values of t.indexOf('a'), t.lastIndexOf('a'), t.indexOf("say") and t.substring(2, 5)?

Solution. First write the indices: b=0, i=1, l=2, g=3, i=4, s=5, a=6, y=7, a=8, r=9. The first 'a' is at index 6 and the last 'a' at index 8. The text "say" starts with the 's' at index 5; the result is 5. substring(2, 5) takes the characters at indices 2, 3 and 4: "lgi". Its length is 5 − 2 = 3.

11.4.2Frequently used methods

Table 11.3 summarizes the most frequently used methods. The program that follows tries all of them on short strings.

Table 11.3: Frequently used String methods. All return a result without changing the original string.
MethodResultReturn type
length()Number of characters (code units)int
charAt(i)The character at position ichar
substring(a, b)The substring from a (included) to b (excluded)String
indexOf(x)The first position of x; −1 if absentint
toLowerCase(), toUpperCase()A new string in lowercase or uppercaseString
trim(), strip()A new string with leading and trailing whitespace removedString
isEmpty(), isBlank()Is the length 0; does it consist only of whitespace?boolean
s0M1e2r3h4a5b6asubstring(1, 4) → "erh"indexOf('a') → 4length() → 7indexOf('z') → -1toLowerCase() → "merhaba"
Figure 11.7: Five methods on s = "Merhaba". substring(1, 4) takes indices 1, 2 and 3: “erh”. indexOf('a') gives the index of the first 'a', 4; since 'z' never occurs, indexOf('z') is −1.
public class CommonMethods {
    public static void main(String[] args) {
        String s = "Merhaba";
        System.out.println(s.length());
        System.out.println(s.charAt(1));
        System.out.println(s.substring(1, 4));
        System.out.println(s.indexOf('a'));
        System.out.println(s.indexOf('z'));
        System.out.println(s.toLowerCase());
        System.out.println(s.toUpperCase());
        String k = "  Ada Can \t";
        System.out.println("[" + k.trim() + "] [" + k.strip() + "]");
        String g = " Ada ";
        System.out.println(g.trim().length() + " " + g.strip().length());
        System.out.println("".isEmpty() + " " + "   ".isEmpty() + " " + "   ".isBlank());
        System.out.println("ab".repeat(3));
    }
}
7
e
erh
4
-1
merhaba
MERHABA
[Ada Can] [Ada Can]
5 3
true false true
ababab

The first seven lines confirm the values in Figure 11.7. The following lines try the whitespace-removing methods. The string k has two spaces at the start and a space and a tab character (\t) at the end. trim() and strip() both remove these and do not touch the space in between: [Ada Can].

The difference between the two methods shows up with rarer characters. trim() removes only characters with codes of 32 and below, that is, ASCII spaces and control characters. strip() recognizes all of Unicode's whitespace characters. The string g has a wide space called the “em space” (U+2003) at both ends. trim() does not recognize this character and the length stays 5; strip() removes it and the length drops to 3. For user input and for copied and pasted text, strip() is safer.

isEmpty() gives true only for a string of length 0. isBlank() gives true for the empty string and for a string made up only of whitespace. So for the three-space string " ", the first is false and the second is true. The repeat(3) in the last line writes the string three times side by side: ababab.

11.4.3Splitting with split

A list separated by commas, a sentence separated by spaces or a date with dots is processed by breaking it into parts. The character that separates the parts is called the delimiter. The split method cuts the string at the places where the delimiters are and returns the parts in a String array.

import java.util.Arrays;

public class SplitReplace {
    public static void main(String[] args) {
        String[] p = "a,b,,c".split(",");
        System.out.println(Arrays.toString(p) + " " + p.length); // [a, b, , c] 4
        String s = "ali veli";
        String t = s.replace('l', 'L');
        System.out.println(t); // aLi veLi
        System.out.println(s); // ali veli
        String[] q = "a,b,,".split(",");
        System.out.println(Arrays.toString(q) + " " + q.length);
        String[] r = ",a,b".split(",");
        System.out.println(Arrays.toString(r) + " " + r.length);
        String[] u = "3.14".split(".");
        System.out.println(u.length);
        String[] v = "3.14".split("\\.");
        System.out.println(Arrays.toString(v));
    }
}
[a, b, , c] 4
aLi veLi
ali veli
[a, b] 2
[, a, b] 3
0
[3, 14]

The first six lines of the program are the example from the slides; the following lines try the other rules of split. "a,b,,c".split(",") cuts the text at three commas and produces four parts: "a", "b", "" and "c". Between two consecutive commas there is nothing; this empty string also goes into the array. Arrays.toString(p) prints the array in readable form: [a, b, , c]. The gap between the two commas is where the empty part sits. Figure 11.8 shows this split.

0a1,2b3,4,5ctext0a1b2""3cp4 parts from the commas
Figure 11.8: "a,b,,c".split(","). The six-character text above is cut at the commas at indices 1, 3 and 4. The array p below has four cells; the cell at index 2 is the empty string.

The additional lines show three rules of split:

  • Trailing empty parts are dropped. "a,b,,".split(",") gives two parts, not four: [a, b]. The two trailing empty parts do not go into the array.
  • A leading empty part is kept. ",a,b".split(",") gives three parts: [, a, b]. The empty text before the first comma counts as a part.
  • The delimiter is a regular expression. The text given to split is not a plain character but a pattern. In the pattern language, the dot means “any character”. So "3.14".split(".") cuts at every character, all the parts are empty, and once the trailing empty parts are dropped the array length is 0. To split at the dot itself, split("\\.") is written and the result is [3, 14].
Definition 11.5

A regular expression is a small language that describes a text pattern. Some characters have a special meaning in this language: . means any character, + means “one or more”, [0-9] means any digit and \s means any whitespace character. To use a special character with its own meaning, a backslash is put in front of it. Because the backslash itself is written \\ in a Java string literal, the pattern takes the form "\\." or "\\s+".

Example 11.3

How many parts do "23.10.2026".split("\\.") and "elma, armut,kiraz".split(",") give, and what are the parts?

Solution. The first string has two dots; three parts come out: "23", "10", "2026". The second string has two commas; again three parts come out: "elma", " armut", "kiraz". The space at the start of the second part is kept, because the delimiter is only the comma. To remove the space too, either strip() is applied to each part or the delimiter is given as ",\\s*" (a comma followed by zero or more spaces).

11.4.4replace and regular expressions

replace returns a new string in which all the matches in a string have been replaced with another text. Lines 4–7 of the same program show this: s.replace('l', 'L') turns the two 'l' letters in "ali veli" (indices 1 and 6) into uppercase and returns "aLi veLi". s stays the same; the last line again prints ali veli. Figure 11.9 shows the two objects side by side.

0a1l2i34v5e6l7is0a1L2i34v5e6L7itreplace('l','L'): new object
Figure 11.9: t = s.replace('l', 'L'). Top: the “ali veli” object that s points to stays unchanged. Bottom: t points to the new object with 'L' at indices 1 and 6.

The family of replacement methods has four members, and the difference between them lies in the kind of thing being searched for. Table 11.4 gives the examples from the slides together with JDK 21 output.

Table 11.4: The replacement methods. The result column is the real output of the program.
CallResultExplanation
"banana".replace('a', 'o')bononoevery 'a' character becomes 'o'
"banana".replace("an", "AN")bANANaplain-text search; left to right, without overlap
"a1b22c333".replaceAll("[0-9]+", "#")a#b#c#each group of digits becomes a single #
"a1b22c333".replaceFirst("[0-9]+", "#")a#b22c333only the first match is replaced
"Ada Can Ece".replaceAll(" +", " ")Ada Can Ececonsecutive spaces are reduced to one

replace searches for plain text, while replaceAll and replaceFirst search for a regular expression. The pattern [0-9]+ means “one or more digits”. In "a1b22c333" there are three groups of digits: 1, 22 and 333. Each group matches as a whole and is replaced with a single #. The pattern " +" means “one or more spaces”; gaps of two and three spaces are reduced to one space.

Common mistake

Using replaceAll to replace plain text. If the text searched for contains special characters such as the dot, plus or star, the result is unexpected. "1.5".replace(".", ",") gives the expected 1,5. "1.5".replaceAll(".", ","), however, replaces every character and produces ,,,; the dot means “any character”. For plain text replace is enough, and it too replaces all the matches.

11.4.5join, valueOf and format

Three static methods are called with the class name, not through an object: String.join, String.valueOf and String.format.

  • String.join(", ", "Ada", "Can", "Ece") joins the parts with a delimiter between them: Ada, Can, Ece. It can be thought of as the opposite of split.
  • String.valueOf(3.5) converts a value to a string: "3.5". If a character array is given, it joins the characters: String.valueOf(new char[]{'h', 'i'}) returns "hi".
  • String.format uses the same format string as printf but does not print the result to the screen; it returns it as a string.

Table 11.5 gives three examples of format with two different locales. The whole program is the class ReplaceTable; it was run once on a Java virtual machine with an English (US) locale and once on one with a Turkish locale.

Table 11.5: String.format examples. In the last two rows no locale is given; the result depends on the machine's setting.
Callon an en_US machineon a tr_TR machine
String.format(Locale.US, "%.2f", 3.14159)3.143.14
String.format(Locale.US, "%5d|%-5d|%05d", 42, 42, 42)␣␣␣42|42␣␣␣|00042␣␣␣42|42␣␣␣|00042
String.format(Locale.US, "%,d", 1234567)1,234,5671,234,567
String.format("%.2f", 3.14159)3.143,14
String.format("%,d", 1234567)1,234,5671.234.567

The ␣ mark in the table is there to make the spaces in the results visible. %5d right-aligns the number in a field of 5 characters; since 42 is two characters, three spaces come before it. %-5d left-aligns and puts the spaces at the end. %05d pads with zeros instead of spaces. %,d adds a thousands separator. %.2f rounds the number to two digits after the decimal point.

The rows given Locale.US give the same result on every machine. The last two rows, with no locale given, follow the language of the machine: on a computer with a Turkish setting the decimal separator is a comma and the thousands separator a dot. For numbers going to a file or to another program, the locale is given explicitly; for numbers shown to a user on the screen, the machine's setting may be appropriate.

11.4.6Substring bounds

substring is the method on which mistakes are most often made. An easy way to remember the rule is to write the indices not on the characters but on the lines between them. In Figure 11.10, there are eight lines, from 0 to 7, among the seven characters of the string "PROGRAM". substring(a, b) takes the characters that lie between line a and line b.

PROGRAM01234567s.substring(0, 3) → "PRO" PROGRAM01234567s.substring(3, 7) → "GRAM" PROGRAM01234567s.substring(2, 2) → "" PROGRAM01234567✗ no 9s.substring(5, 9) → StringIndexOutOfBoundsException
Figure 11.10: Four calls on s = "PROGRAM". Between lines 0 and 3 is “PRO”. The end can be length() = 7: between 3 and 7 is “GRAM”. If the start equals the end, there are no characters in between: “”. Because there is no line 9, substring(5, 9) gives an error.
Definition 11.6

A substring is a part of a string made up of consecutive characters. s.substring(a, b) returns the substring that starts at the character at index a and ends before the character at index b; its length is b − a. The valid range is 0 ≤ a ≤ b ≤ s.length(). s.substring(a) gives the part from index a to the end of the string and is the same as s.substring(a, s.length()).

public class Substrings {
    public static void main(String[] args) {
        String s = "PROGRAM";
        System.out.println(s.substring(0, 3));
        System.out.println(s.substring(3, 7));
        System.out.println(s.substring(3));
        System.out.println("[" + s.substring(2, 2) + "]");
        System.out.println("[" + s.substring(7) + "]");
        System.out.println(s.substring(0, 3).length() + " " + s.substring(2, 5));
        System.out.println(s.substring(5, 9));
    }
}
PRO
GRAM
GRAM
[]
[]
3 OGR
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [5, 9) out of bounds for length 7

The output confirms each rule. substring(0, 3) takes three characters: 3 − 0 = 3. substring(3, 7) and substring(3) give the same result, because the length of the string is 7. substring(2, 2) is the empty string; this is not an error, it means “take zero characters”. substring(7) is also the empty string: 7 is the last line and there are no characters after it. The substring(5, 9) on the last line throws an exception, because the end exceeds the length. The message says that the range [5, 9) is invalid for a string of length 7. The square bracket shows that the start is included and the round bracket that the end is excluded; this is the half-open interval notation of mathematics.

If the start is greater than the end, an exception is thrown too:

public class SubstringReversed {
    public static void main(String[] args) {
        String s = "PROGRAM";
        System.out.println(s.substring(5, 3));
    }
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [5, 3) out of bounds for length 7
Table 11.6: The substring calls for s = "PROGRAM" (length 7).
CallCondition 0 ≤ a ≤ b ≤ 7ResultLength
s.substring(0, 3)0 ≤ 0 ≤ 3 ≤ 7 holds"PRO"3
s.substring(2, 5)holds"OGR"3
s.substring(3, 7)holds"GRAM"4
s.substring(2, 2)holds (a = b)""0
s.substring(7)holds (a = 7)""0
s.substring(5, 9)9 ≤ 7 is falseexception–
s.substring(5, 3)5 ≤ 3 is falseexception–
Common mistake

Taking the second parameter of substring to be “how many characters to take”. "PROGRAM".substring(2, 3) gives not the three characters starting at index 2 but only one character (“O”). The second parameter is the end position, not the length. To take k characters, write substring(a, a + k).

11.4.7Application: taking an email address apart

When indexOf and substring are used together, a text can be split on the two sides of a delimiter. An email address is split by the @ sign into a username and a domain name:

String email = "ali@gru.edu";
int at = email.indexOf('@');
String user = email.substring(0, at);
String domain = email.substring(at + 1);
char first = email.charAt(0);
System.out.println(user + " / " + domain);
System.out.println(Character.toUpperCase(first));
ali / gru.edu
A

In seven lines the program does this: it finds the position of @, takes what comes before and after it separately, reads the first character and converts it to uppercase. Table 11.7 is the trace table; Figure 11.11 shows the two cutting points.

Table 11.7: The trace table of the email program. email = "ali@gru.edu" (11 characters, indices 0–10).
LineOperationVariableOutput
2indexOf('@'): @ is at index 3at = 3
3substring(0, 3): indices 0, 1, 2user = "ali"
4substring(4): from 4 to the enddomain = "gru.edu"
5charAt(0)first = 'a'
6concatenationali / gru.edu
7Character.toUpperCase('a')A
0a1l2i3@4g5r6u7.8e9d10u▲ atemail 0a1l2i3@4g5r6u7.8e9d10u▲ atemail
Figure 11.11: Splitting the string “ali@gru.edu”. Top: substring(0, at), indices 0–2 to the left of @, “ali”. Bottom: substring(at + 1), from index 4 after @ to the end, “gru.edu”. The @ character itself is in neither part.

Two details deserve attention. The first is the reason for writing at + 1: if substring(at) were written, the domain would be "@gru.edu". The second is the return type of charAt. first is a char, and to convert it to uppercase, the toUpperCase method of the Character class, not of String, is used. This method takes a char and returns a char.

The weak point of the program is the case where there is no @ in the address. Then indexOf returns −1 and the call substring(0, -1) throws an exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [0, -1) out of bounds for length 10

A robust program first checks the result of the search:

public class EmailSafe {
    public static void main(String[] args) {
        String[] addresses = {"ali@gru.edu", "aligru.edu"};
        for (String email : addresses) {
            int at = email.indexOf('@');
            if (at < 0) {
                System.out.println(email + ": no @");
            } else {
                System.out.println(email.substring(0, at) + " / " + email.substring(at + 1));
            }
        }
    }
}
ali / gru.edu
aligru.edu: no @
Example 11.4

To produce the output “KAYA, ece” from the address s = "ece.kaya@uni.tr", which indices are used?

Solution. The address has 15 characters; the indices are 0–14. s.indexOf('@') is 8; s.substring(0, 8) gives "ece.kaya". In this new string the dot is at index 3. substring(0, 3) gives "ece" and substring(4) gives "kaya". "kaya".toUpperCase() returns a new string "KAYA". When the program is run, the output is:

KAYA, ece

11.5Comparison

Asking whether two strings are the same is one of the most frequent jobs in programming: is the entered password correct, did the user type “yes”, do two students have the same name? For numbers, this question is asked with ==. For strings, == does not ask the expected question.

11.5.1== and equals

Because a String variable holds a reference, a == b compares two references. The question becomes “do the two variables point to the same object?”. Even if two separate objects carry the same characters, == gives false. To compare contents, the equals method is used.

Definition 11.7

Reference comparison (a == b) tests whether two variables point to the same object. Content comparison (a.equals(b)) tests whether two strings have the same length and carry the same characters at the same positions. The equality of strings is always asked with equals.

String a = "Giresun";
String b = new String("Giresun");
String c = "Giresun";
System.out.println(a == b);      // false
System.out.println(a == c);      // true
System.out.println(a.equals(b)); // true
false
true
true

The program creates three variables and makes three comparisons. Figure 11.12 gives the final state of memory, and Table 11.8 the line-by-line trace.

StackHeapString pool (constants)GiresunGiresunseparate object with newabc
Figure 11.12: Memory after the three lines. a and c point to the single “Giresun” object in the string pool. b points to a separate “Giresun” object created on the heap with new. The two objects have the same contents and different locations.
Table 11.8: The trace table of the == and equals program.
LineOperationResultReason
1a = "Giresun"a → poolplaced in the constant pool
2b = new String("Giresun")b → new objectnew always creates a separate object
3c = "Giresun"c → poolthe same constant; the object in the pool is shared
4a == bfalsethe two arrows go to different objects
5a == ctrueboth arrows are on the same object
6a.equals(b)truethe characters are equal one by one: G=G, i=i, …, n=n

The true on line 5 is misleading. That a == c comes out true is due not to the contents being equal but to the two constants sharing the same object in the pool. If one of the strings had been read from the keyboard, come from a file or been produced by an operation, it would be a separate object and == would give false. Where a string comes from is not always clear from looking at the code. So the rule is simple: for contents, equals.

Common mistake

Checking the answer typed by the user with if (answer == "yes"). The string read by Scanner is always a new object; even if the user types “yes”, the condition comes out false. The program compiles and gives no error; it just behaves wrongly. The correct form is if (answer.equals("yes")).

11.5.2Comparison methods

Besides equals, four more comparison methods are often used. Table 11.9 gives them with examples; the results are the real output of the program.

Table 11.9: Comparison methods.
MethodPurposeExampleResult
equalscontent equality"abc".equals("abc")true
equalsIgnoreCaseequality that ignores letter case"Java".equalsIgnoreCase("JAVA")true
startsWithstarts with a given text"Giresun".startsWith("Gir")true
endsWithends with a given text"Giresun".endsWith("sun")true
compareTolexicographic order: negative, 0 or positive"elma".compareTo("armut")4
GiresunstartsWith("Gir") → trueendsWith("sun") → trueequals("giresun") → falseequalsIgnoreCase("giresun") → true
Figure 11.13: The string “Giresun” starts with “Gir” and ends with “sun”. equals("giresun") gives false, because 'G' and 'g' are different characters. equalsIgnoreCase("giresun") gives true, because it ignores letter case.
public class ComparisonMethods {
    public static void main(String[] args) {
        System.out.println("abc".equals("abc"));
        System.out.println("Java".equalsIgnoreCase("JAVA"));
        System.out.println("Giresun".startsWith("Gir"));
        System.out.println("Giresun".endsWith("sun"));
        System.out.println("elma".compareTo("armut"));
        System.out.println("Giresun".equals("giresun"));
        System.out.println("Giresun".equalsIgnoreCase("giresun"));
        System.out.println("Giresun".startsWith("gir"));
    }
}
true
true
true
true
4
false
true
false

The last three lines show case sensitivity. equals, startsWith and endsWith compare characters as they are: "Giresun".startsWith("gir") is false. Where letter case does not matter (such as a command being typed as “YES”, “Yes” or “yes”), equalsIgnoreCase is used.

11.5.3compareTo and lexicographic order

Besides equality, the order of two strings can be asked too: which one comes first in a dictionary? This order is called lexicographic order. a.compareTo(b) returns an integer. If the result is negative, a comes first; if zero, the two are equal; if positive, a comes later.

Definition 11.8

a.compareTo(b) compares the two strings character by character, starting at the beginning. There are two cases:

  1. If the first differing character is at position k, the result is a.charAt(k) − b.charAt(k); that is, the difference of the codes of the two characters.
  2. If all the characters of the shorter string are the same as the beginning of the longer one, the result is a.length() − b.length(); that is, the length difference.

If the two strings are exactly the same, the second rule gives 0.

String x = "elma";
String y = "armut";
System.out.println(x.compareTo(y)); // 4
String k = "kedi";
System.out.println(k.compareTo("kediler")); // -3

The two examples in the slides exercise the two rules separately. Figure 11.14 shows the critical step of each.

  • "elma".compareTo("armut"): at position 0, 'e' meets 'a' and they differ. The result is 'e' − 'a' = 101 − 97 = 4. Because it is positive, “elma” comes after “armut”. The lengths of the strings (4 and 5) do not enter the result at all; the first differing character decides.
  • "kedi".compareTo("kediler"): in the first four positions k=k, e=e, d=d, i=i. Then “kedi” ends; no differing character has been found. The result is the length difference: 4 − 7 = −3. Because it is negative, the shorter “kedi” comes first.
0e1l2m3ax0a1r2m3u4ty'e' (101) - 'a' (97) = 4 0k1e2d3ik0k1e2d3i4l5e6rarg4 - 7 = -3 (length difference)
Figure 11.14: The two compareTo rules. Top: “elma” and “armut”: the first characters differ and the result is the code difference, 101 − 97 = 4. Bottom: “kedi” and “kediler”: the first four characters are equal and the result is the length difference, 4 − 7 = −3.

The program below makes eight more comparisons besides the two lines in the slides:

public class CompareTo {
    public static void main(String[] args) {
        String x = "elma";
        String y = "armut";
        System.out.println(x.compareTo(y)); // 4
        String k = "kedi";
        System.out.println(k.compareTo("kediler")); // -3
        System.out.println(y.compareTo(x));
        System.out.println("Ali".compareTo("ali"));
        System.out.println("abc".compareTo("abc"));
        System.out.println("Zeytin".compareTo("armut"));
        System.out.println("çilek".compareTo("dut"));
        System.out.println("ılgın".compareTo("incir"));
        System.out.println("Ali".compareToIgnoreCase("ali"));
        System.out.println("10".compareTo("9"));
    }
}
4
-3
-4
-32
0
-7
131
200
0
-8

Table 11.10 explains each result by the rule.

Table 11.10: How the compareTo results are computed. The code column gives the Unicode codes of the first differing characters.
CallFirst differenceCalculationResult
"elma".compareTo("armut")position 0: e / a101 − 974
"kedi".compareTo("kediler")none4 − 7−3
"armut".compareTo("elma")position 0: a / e97 − 101−4
"Ali".compareTo("ali")position 0: A / a65 − 97−32
"abc".compareTo("abc")none3 − 30
"Zeytin".compareTo("armut")position 0: Z / a90 − 97−7
"çilek".compareTo("dut")position 0: ç / d231 − 100131
"ılgın".compareTo("incir")position 0: ı / i305 − 105200
"Ali".compareToIgnoreCase("ali")case is ignored–0
"10".compareTo("9")position 0: 1 / 949 − 57−8

The lower half of the table shows where compareTo departs from true dictionary order:

  • Uppercase letters come before lowercase ones. The codes of uppercase letters are in the range 65–90, and those of lowercase letters in 97–122. This is why “Zeytin” comes before “armut”.
  • Turkish letters fall to the end. The codes of letters such as 'ç' (231), 'ı' (305) and 'ş' (351) are greater than those of all English letters. “çilek” comes after “dut”, and “ılgın” after “incir”. In the Turkish alphabet, however, ç comes before d and ı before i.
  • Numbers are compared like text. “10” comes before “9”, because the first characters are '1' and '9'. To compare the values of numbers, they must first be converted to numbers with Integer.parseInt.

For sorting that fits the Turkish alphabet, Java's java.text.Collator class is used. A Collator knows the sorting rules of a language. The program below sorts the same list of fruits first in the order of compareTo, then with a Turkish Collator:

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

public class Sorting {
    public static void main(String[] args) {
        String[] fruits = {"zeytin", "çilek", "armut", "Elma", "ıhlamur", "incir", "üzüm", "dut"};
        String[] a = fruits.clone();
        Arrays.sort(a);
        System.out.println(Arrays.toString(a));
        String[] b = fruits.clone();
        Arrays.sort(b, Collator.getInstance(Locale.forLanguageTag("tr")));
        System.out.println(Arrays.toString(b));
    }
}
[Elma, armut, dut, incir, zeytin, çilek, üzüm, ıhlamur]
[armut, çilek, dut, Elma, ıhlamur, incir, üzüm, zeytin]

In the first line, “Elma”, which starts with an uppercase letter, has moved to the front, and “çilek”, “üzüm” and “ıhlamur”, which start with Turkish letters, have fallen to the end. The second line is the order of the Turkish alphabet: a, ç, d, e, ı, i, ü, z. A Collator also treats the uppercase–lowercase difference as secondary; “Elma” takes the place of the letter e.

Example 11.5

What are the values of "kalem".compareTo("kale"), "kale".compareTo("kalp") and "Kale".compareTo("kale")?

Solution. In the first call “kale” is the beginning of “kalem”; there is no differing character. The result is the length difference: 5 − 4 = 1. In the second call the first three characters are equal; at position 3, 'e' meets 'p'. The result is 101 − 112 = −11. In the third call the first characters are 'K' (75) and 'k' (107). The result is 75 − 107 = −32. The difference between the uppercase and lowercase forms of the same letter is 32 for all English letters.

11.5.4Turkish characters and the locale

Converting between uppercase and lowercase is simple in most languages: a ↔ A, b ↔ B. In Turkish, however, there are two separate letters i, dotted and dotless: i ↔ İ and ı ↔ I. In English these pairs are i ↔ I. The lowercase of the same letter “I” is “i” in English and “ı” in Turkish. Java solves this difference with the locale. A locale is a java.util.Locale object that carries the writing rules of a language and region.

Definition 11.9

toLowerCase(Locale) and toUpperCase(Locale) do the letter conversion according to the rules of the given language. The locale for Turkish is obtained with Locale.forLanguageTag("tr") and for English with Locale.ENGLISH. The parameterless toLowerCase() and toUpperCase() use the default locale of the machine on which the program runs.

import java.util.Locale;

public class TurkishLocale {
    public static void main(String[] args) {
        Locale tr = Locale.forLanguageTag("tr");
        System.out.println("TITLE".toLowerCase(Locale.ENGLISH));
        System.out.println("TITLE".toLowerCase(Locale.forLanguageTag("tr")));
        System.out.println("i".toUpperCase(tr));
        System.out.println("i".toUpperCase(Locale.ENGLISH));
        System.out.println("I".toLowerCase(tr));
        System.out.println("ISPARTA".toLowerCase(tr));
        System.out.println("ısparta".toUpperCase(tr));
        System.out.println("TITLE".toLowerCase(tr).equals("title"));
        System.out.println("title".equalsIgnoreCase("TITLE"));
        System.out.println("istanbul".toUpperCase(tr) + " " + "istanbul".toUpperCase(Locale.ENGLISH));
        System.out.println("İZMİR".toLowerCase(tr) + " " + "İZMİR".toLowerCase(tr).length());
        System.out.println("İZMİR".toLowerCase(Locale.ENGLISH).length() + " " + "İZMİR".length());
        System.out.println("ISPARTA".equalsIgnoreCase("ısparta") + " " + "i".equalsIgnoreCase("İ"));
    }
}
title
tıtle
İ
I
ı
ısparta
ISPARTA
false
true
İSTANBUL ISTANBUL
izmir 5
7 5
true true

Table 11.11 explains the results of the first seven calls with the rules of the two languages.

Table 11.11: Turkish and English letter conversion. tr = Locale.forLanguageTag("tr").
CallResultRule
"TITLE".toLowerCase(Locale.ENGLISH)titleEnglish: I → i
"TITLE".toLowerCase(Locale.forLanguageTag("tr"))tıtleTurkish: I → ı
"i".toUpperCase(tr)İTurkish: i → İ
"i".toUpperCase(Locale.ENGLISH)IEnglish: i → I
"I".toLowerCase(tr)ıTurkish: I → ı
"ISPARTA".toLowerCase(tr)ıspartaTurkish: I → ı
"ısparta".toUpperCase(tr)ISPARTATurkish: ı → I

The following lines show the effect of the conversion on equality tests. Because "TITLE".toLowerCase(tr) gives “tıtle”, it is not equal to "title". equalsIgnoreCase, on the other hand, compares characters one by one with a language-independent rule and gives true. “istanbul” becomes “İSTANBUL” under Turkish rules and “ISTANBUL” under English rules. The Turkish lowercase of “İZMİR” is the five-letter “izmir”. When it is lowercased with English rules, however, each “İ” turns into an “i” plus a separate dot mark added on top of it. The result looks like “izmir” on the screen but has length 7. This text does not pass an equals test against “izmir”.

The most insidious problem is in the parameterless calls. The program below runs the same code on two different machines: one has an English (US) locale and the other a Turkish one.

import java.util.Locale;

public class DefaultLocale {
    public static void main(String[] args) {
        System.out.println(Locale.getDefault());
        String file = "ARSIV.ZIP".toLowerCase();
        System.out.println(file);
        System.out.println(file.endsWith(".zip"));
        System.out.println("title".toUpperCase());
        System.out.println("ARSIV.ZIP".toLowerCase(Locale.ENGLISH).endsWith(".zip"));
        System.out.printf("%.2f%n", 17.5);
    }
}

On the machine with the English setting, the output is:

en_US
arsiv.zip
true
TITLE
true
17.50

On the machine with the Turkish setting, the same program prints:

tr_TR
arsıv.zıp
false
TİTLE
true
17,50

The program checks whether a file name ends with “.zip”. On the English machine, “ARSIV.ZIP” becomes “arsiv.zip” when lowercased and the check passes. On the Turkish machine the same line produces “arsıv.zıp” and the check fails. There is no change in the code; only the language of the computer is different. "title".toUpperCase() also gives “TİTLE” on the Turkish machine. The fifth line, which gives the locale explicitly, prints true on both machines. The printf on the last line is also affected by the locale: the decimal separator is a dot on one machine and a comma on the other.

Common mistake

Converting technical text such as keywords, command names, file extensions and email addresses with the parameterless toLowerCase() or toUpperCase(). The program works correctly on the developer's computer and breaks on a computer with a Turkish setting. This bug is known in the software world as “the Turkish i problem”. For technical text, Locale.ENGLISH (or the language-independent Locale.ROOT) is given explicitly, and for Turkish text Locale.forLanguageTag("tr").

In older sources the Turkish locale is also created as new Locale("tr"). This constructor has been deprecated since JDK 19; the JDK 21 compiler gives a warning for this line with the -Xlint option. Locale.forLanguageTag("tr") or Locale.of("tr") is used instead.

Example 11.6

A program converts the name of a province typed by the user to uppercase and compares it with "IĞDIR". The user types “ığdır”. What is the result with toUpperCase(Locale.ENGLISH) and with toUpperCase(tr)?

Solution. The uppercase of the dotless “ı” is “I” in both languages; English rules also recognize this Turkish letter. Both calls give “IĞDIR” and the comparison passes. If the user had typed “iğdir”, the situation would change: with Turkish rules it would give “İĞDİR” and with English rules “IĞDIR”. In a Turkish text the Turkish rules are the correct ones; in this case it turns out that “iğdir” was misspelled.

11.6Memory: the string pool

The same string literal can occur in many places in a program: “Giresun”, “yes”, the empty string. Creating a separate object for each would waste memory. This is why Java gathers the literals in a common pool.

11.6.1The pool and new

Definition 11.10

The string pool is the region of memory in which the Java virtual machine keeps string literals. All literals with the same contents share a single object in the pool. new String(...), however, does not look at the pool and creates a new object on the heap on every call.

Sharing is safe only because strings are immutable. If they could be changed, a change made through one variable would affect all the variables using the same literal. Figure 11.15 shows the state of three variables.

StackHeapString pool (constants)GiresunsharedGiresunnewacb
Figure 11.15: The string pool. Because a and c were created with the same literal, they share the single “Giresun” object in the pool. Because b was created with new, it points to a separate object on the heap.
public class Pool {
    public static void main(String[] args) {
        String a = "Giresun";
        String c = "Giresun";
        String b = new String("Giresun");
        String d = new String("Giresun");
        System.out.println((a == c) + " " + (a == b) + " " + (b == d));
        System.out.println(a.equals(b) + " " + b.equals(d));
        System.out.println((b.intern() == a) + " " + (b.intern() == b));
    }
}
true false false
true true
true false

The first line makes three reference comparisons. a == c is true: both point to the object in the pool. a == b is false: b is a separate object on the heap. b == d is false too: two new calls produce two separate objects. The equals tests on the second line are all true, because the contents are the same.

11.6.2Constant concatenation and intern

Whether a string comes from the pool is not always easy to read from the code. The program below shows two subtle cases of this:

String a = "a", b = "b";
String r = a + b;
final String f = "a";
System.out.println(("a" + "b") == "ab");  // true
System.out.println((f + "b") == "ab");    // true
System.out.println(r == "ab");            // false
System.out.println(r.equals("ab"));       // true
System.out.println(r.intern() == "ab");   // true
true
true
false
true
true

The five results are explained as follows:

  1. ("a" + "b") == "ab" is true. Because both operands are constants, the compiler does the concatenation before the program runs. In the compiled code, the constant "ab" appears directly instead of "a" + "b", and this constant comes from the pool.
  2. (f + "b") == "ab" is true too. f is declared final and initialized with a constant. Because its value can never change, the compiler treats it as a constant as well.
  3. r == "ab" is false. In the line r = a + b, a and b are ordinary variables. The concatenation is done at run time and the result is a new object on the heap.
  4. r.equals("ab") is true; the contents are the same.
  5. r.intern() == "ab" is true. The intern() method looks at the pool: if a string with the same contents exists there, it returns that one; if not, it adds the string to the pool and returns it. The returned reference is the "ab" in the pool.

Expressions whose value is known at compile time are called constant expressions: string literals, final constants and combinations of them. The result of a constant expression is put in the pool. Every concatenation that involves a variable produces a new object.

The effect of intern can also be seen in the last line of the Pool program. b.intern() == a is true: the contents of b exist in the pool, and intern returns the object in the pool. b.intern() == b is false: b itself is an object outside the pool. In practice intern is rarely needed; it is used here to make the workings of the pool visible.

Common mistake

Seeing == give the right result in a few trials and continuing to compare strings with ==. Because the literals used in the trials are shared in the pool, == comes out right by coincidence. The same code gives a wrong result when the text comes from the keyboard or from a file. == being true shows not that the contents are equal but that the object is the same.

11.6.3Null-safe comparison

equals is a method and is called through an object. If the variable is null, the call cannot be made and a NullPointerException occurs. Writing the same comparison the other way round removes this problem:

public class NullSafe {
    public static void main(String[] args) {
        String x = null;
        System.out.println("constant".equals(x));
        System.out.println(x.equals("constant"));
    }
}
false
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "x" is null

In the line "constant".equals(x), the method is called on "constant", a real object. When the parameter is null, equals does not raise an error; it simply returns false. In the line x.equals("constant"), however, the method is called through null and the program stops. This is why the constant is written on the left: "yes".equals(answer) is safe even if answer is null.

11.7Text input with Scanner

The java.util.Scanner class is used to read text from the keyboard. The class has two methods for reading text: next() reads a word and nextLine() reads a line. The key to understanding the behavior of the two methods is the buffer, where the characters coming from the keyboard wait.

11.7.1next and nextLine

When the user types something and presses Enter, the characters typed and the end-of-line character go into the buffer. In these notes the end-of-line character is shown as ⏎. Each read method of Scanner takes characters from the start of the buffer and moves the reading position forward. Characters that have been read are not read again.

Definition 11.11

next() skips leading spaces and line ends, then reads the non-whitespace characters up to the first space or line end. This part is called a token. The space or ⏎ after the token stays in the buffer. nextLine(), on the other hand, reads everything from its current position to the end of the line, spaces included. It consumes the ⏎ but does not add it to the result.

import java.util.Scanner;
// ...
Scanner in = new Scanner(System.in);
String word = in.next();
in.nextLine();
String line = in.nextLine();

Figure 11.16 summarizes how this code works when the buffer holds “Ada⏎Merhaba dünya⏎”. next() reads “Ada” and leaves the ⏎. The nextLine() in between consumes only that ⏎ and returns the empty string. The next nextLine() reads the whole second line.

Ada⏎Merhaba dünya⏎① next() → "Ada"③ nextLine() → "Merhaba dünya"② nextLine() → "" (only the ⏎ is consumed)buffer: Ada⏎Merhaba dünya⏎⏎ = end of line (Enter)
Figure 11.16: Three reads while the buffer is “Ada⏎Merhaba dünya⏎”. ① next() reads “Ada”. ② nextLine() consumes only the ⏎ and returns "". ③ nextLine() reads “Merhaba dünya”.

That next() stops at whitespace makes it easy to read the words on a line one by one. “␣␣Ada␣␣␣Can␣Ece␣Su” is entered on a single line to the following program (␣ shows a space):

import java.util.Scanner;

public class NextWords {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String a = in.next();
        String b = in.next();
        String c = in.nextLine();
        System.out.println("[" + a + "] [" + b + "] [" + c + "]");
    }
}
[Ada] [Can] [ Ece Su]

The first next() skips the two leading spaces and reads “Ada”. The second next() skips the three spaces in between and reads “Can”. nextLine() takes the rest of the line as it is: the space at its start also goes into the result and “␣Ece␣Su” is read. nextLine() does not skip spaces.

11.7.2Tracing the buffer step by step

The trace example in the slides is five lines long:

Scanner in = new Scanner(System.in);
String word = in.next();
in.nextLine();
String line = in.nextLine();
System.out.println(word + " | " + line);

The program is run once. The user first types “Ada” and presses Enter, then types “Giresun Merkez” and presses Enter. The output is:

Ada | Giresun Merkez
Table 11.12: Tracing the Scanner buffer. The buffer column shows the characters after the reading position that have not been read yet.
StepLineEventUnread bufferResult
11Scanner is attached to the keyboard(empty)
22next() finds nothing to read and waits; the user enters “Ada⏎”Ada⏎
32next() reads up to a space or ⏎⏎word = "Ada"
43nextLine() reads up to ⏎ and consumes the ⏎(empty)"" (discarded)
54nextLine() waits; the user enters “Giresun Merkez⏎”Giresun␣Merkez⏎
64nextLine() reads the whole line and consumes the ⏎(empty)line = "Giresun Merkez"
75printing(empty)Ada | Giresun Merkez
Keyboard buffer (System.in)Ada⏎▲ reading position Keyboard buffer (System.in)Ada⏎▲ reading position Keyboard buffer (System.in)Ada⏎Giresun␣Merkez⏎reading position ▲
Figure 11.17: The keyboard buffer at steps 3, 4 and 6 of the table. Characters that have been read are faded, and the reading position is shown with ▲. At step 3, next() has read “Ada” and the ⏎ is left in the buffer. At step 4, nextLine() has consumed the ⏎. At step 6, the second line has also been read completely.

The result of the call in.nextLine(); on line 3 is not assigned to any variable. The only job of this line is to clear the ⏎ left in the buffer. What happens if the line is deleted? The nextLine() on line 4 finds the leftover ⏎, returns the empty string at once and gives the user no chance to type the second line. The program below shows this; the input is again the same:

import java.util.Scanner;

public class BufferBug {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String word = in.next();
        String line = in.nextLine();
        System.out.println(word + "|" + line + "|");
    }
}
Ada||

line is the empty string; there is nothing between the two vertical bars. The “Giresun Merkez” the user typed has never been read and has stayed in the buffer.

11.7.3nextLine after nextInt

The same problem appears after methods that read numbers, such as nextInt() and nextDouble(). These methods behave like next(): they read the number and leave the line end in the buffer. The program below wants to read the age first and then the full name. The user enters “19⏎” and “Ada Yılmaz⏎”:

import java.util.Scanner;

public class AgeName {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Age: ");
        int age = in.nextInt();
        System.out.print("Full name: ");
        String name = in.nextLine();
        System.out.println();
        System.out.println("[" + name + "] " + age);
    }
}
Age: Full name:
[] 19

The “Full name:” question appears on the screen but the program does not wait for the answer. nextLine() reads the ⏎ left over after the 19, and name stays empty. The fix is to add a nextLine() that clears the leftover after the number:

import java.util.Scanner;

public class AgeNameFixed {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Age: ");
        int age = in.nextInt();
        in.nextLine();
        System.out.print("Full name: ");
        String name = in.nextLine();
        System.out.println();
        System.out.println("[" + name + "] " + age);
    }
}
Age: Full name:
[Ada Yılmaz] 19

You may notice that the line looks empty after the text “Full name:” in the output. The reason is that the input was supplied from a file: when run from the keyboard, the text typed by the user appears on that line. This is why System.out.println() was added to the program.

Common mistake

Using nextInt() and nextLine() one after the other and not understanding why the second read is “skipped”. The read is not skipped: nextLine() has read the empty line left in the buffer. The rule is this: if a line is to be read after next(), nextInt() or nextDouble(), a nextLine() that consumes the ⏎ is put in between. Another way is to read all the input line by line with nextLine() and convert the numbers with Integer.parseInt.

11.8Concatenation and StringBuilder

The + operator is readable and sufficient for joining a few strings. But if concatenation is done thousands of times inside a loop, the price of immutability becomes noticeable.

11.8.1The cost of using + in a loop

The line s = s + x does not lengthen s. Each time it runs, it produces a new object that carries all the characters of s and x. The old object goes to the garbage. Figure 11.18 shows this for a loop of three iterations.

String + (in a loop)1␣garbage1␣2␣garbage1␣2␣3␣new objectStringBuilder1␣2␣3␣single object
Figure 11.18: Top: concatenation with +; each iteration produces a new object named “1␣”, “1␣2␣”, “1␣2␣3␣”; the earlier ones become garbage. Bottom: StringBuilder, where a single object grows.

The number of characters copied can be computed. Consider a loop that appends a single character on each iteration. On iteration 1 a new object of 1 character is built, on iteration 2 one of 2 characters, and on iteration n one of n characters. The total number of characters copied is:

1 + 2 + 3 + … + n = n(n + 1) / 2

This total is roughly n²/2. For n = 1,000 it is 500,500, and for n = 100,000 it comes to about 5 billion characters. The program below verifies these numbers by counting inside the loop:

public class Cost {
    public static void main(String[] args) {
        for (int n : new int[]{1000, 10000, 100000}) {
            long copied = 0;
            String s = "";
            for (int i = 0; i < n; i++) {
                copied += s.length() + 1;
                s = s + "x";
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < n; i++) {
                sb.append('x');
            }
            System.out.println(n + " " + copied + " " + (s.length() == sb.length()));
        }
    }
}
1000 500500 true
10000 50005000 true
100000 5000050000 true

When n grows tenfold, the number of characters copied grows about a hundredfold: from 500,500 to 50,005,000 and then to 5,000,050,000. This rate of growth is called quadratic growth, and for large values of n the program slows down noticeably. In the second loop, with StringBuilder, each character is written to the buffer once; the total work is proportional to n. The true at the end of the line shows that the two methods produced strings of the same length.

11.8.2Concatenating with StringBuilder

Definition 11.12

StringBuilder is a class that keeps characters in a mutable buffer. The append method adds to the end of the buffer and does not produce a new object. When the contents of the buffer are finished, they are converted to a String with toString(). StringBuilder is also in the java.lang package.

StringBuilder text = new StringBuilder();
for (int i = 1; i <= 3; i++) {
    text.append(i).append(' ');
}
String result = text.toString();
System.out.println(result + "|");
1 2 3 |

Table 11.13 gives the ten steps of the program. The loop variable i runs from 1 to 3, and two appends are made on each iteration: the number and then a space.

Table 11.13: The trace table of the StringBuilder program. ␣ is the space character.
StepLineiCondition / actiontext (buffer)result
11an empty buffer is created""
2211 <= 3 → true""
331append(1).append(' ')"1␣"
422i++; 2 <= 3 → true"1␣"
532append(2).append(' ')"1␣2␣"
623i++; 3 <= 3 → true"1␣2␣"
733append(3).append(' ')"1␣2␣3␣"
824i++; 4 <= 3 → false, the loop ends"1␣2␣3␣"
95toString()"1␣2␣3␣""1␣2␣3␣"
106printing: result + "|""1␣2␣3␣""1␣2␣3␣"
StackHeap1␣2␣3␣StringBuilder (mutable)text StackHeap1␣2␣3␣StringBuilder (mutable)1␣2␣3␣Stringtextresult
Figure 11.19: Top: after step 7, a single StringBuilder object carries the characters “1␣2␣3␣”; no new object has been created during the loop. Bottom: after step 9, toString() has produced a String object separate from the current contents of the buffer, and result points to it.

The form text.append(i).append(' ') on line 3 is noteworthy. append returns the very object it appended to. That is why the second append can be called on the same object. Calls in a row like this are called chaining. The "|" at the end is there only to make the space at the end of the output visible.

append accepts a value of any type: int, char, double, boolean, String. Numbers are appended in their text form. append(1) adds the character 1 to the buffer; it does not perform an addition.

11.8.3The other methods of StringBuilder

Because StringBuilder is mutable, it also has methods that String does not. These change the buffer in place:

public class SbMethods {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java");
        sb.append(21);
        System.out.println(sb + " " + sb.length());
        sb.insert(0, "JDK ");
        System.out.println(sb);
        sb.setCharAt(4, 'j');
        System.out.println(sb);
        sb.deleteCharAt(sb.length() - 1);
        System.out.println(sb);
        sb.reverse();
        System.out.println(sb);
        StringBuilder t = sb;
        t.append('!');
        System.out.println(sb + " " + (t == sb));
        System.out.println(new StringBuilder("ab").equals(new StringBuilder("ab")) + " "
                + new StringBuilder("ab").toString().equals("ab"));
    }
}
Java21 6
JDK Java21
JDK java21
JDK java2
2avaj KDJ
2avaj KDJ! true
false true
Table 11.14: The StringBuilder methods and their effects in the program.
CallEffectBuffer
new StringBuilder("Java")initial contentsJava
append(21)appends at the endJava21 (length 6)
insert(0, "JDK ")inserts at position 0JDK Java21
setCharAt(4, 'j')changes the character at position 4JDK java21
deleteCharAt(length() - 1)deletes the last characterJDK java2
reverse()reverses the buffer2avaj KDJ

The last two lines of the program show two important differences. StringBuilder t = sb; does not create a new buffer; t points to the same object. t.append('!') therefore changes sb too, and t == sb is true. With mutable objects, sharing leads to side effects of this kind; with String such a case cannot occur. The second difference is in comparison: the equals method of StringBuilder looks at the reference, not the contents. For two buffers with the same contents “ab”, equals gives false. To compare contents, toString() is called first.

Example 11.7

After a loop that starts with StringBuilder sb = new StringBuilder("ab"); and does sb.append(i).append('-') on each iteration from 1 to 3, the lines String s = sb.toString(); sb.reverse(); run. What does s + " " + sb print?

Solution. The loop turns the buffer from “ab” into “ab1-”, then “ab1-2-”, then “ab1-2-3-”. toString() produces a String separate from the current contents: s = “ab1-2-3-”. reverse() reverses only the buffer: “-3-2-1ba”. s is not affected, because it is a separate and immutable object. In the concatenation, toString() is called automatically for sb. The program output:

ab1-2-3- -3-2-1ba

Which one is chosen when? For joining a few parts once, + is readable and sufficient; the Java compiler already turns one-line concatenations of this kind into efficient code. StringBuilder is used when text is built inside a loop or from a large number of parts whose count is not known in advance.

11.9Applications

All the programs in this section share the same skeleton. A loop goes through the characters of the string in order or from both ends. Each character is read with charAt and a decision is made. What distinguishes the programs from one another is the job done at each step.

11.9.1Reversing a string

To reverse a string, the characters are read from the end to the start and appended to a new string. The program in the slides does this in two ways: first with a hand-written loop, then with the ready-made method of StringBuilder.

String s = "Java";
String rev = "";
for (int i = s.length() - 1; i >= 0; i--)
  rev += s.charAt(i);
System.out.println(rev);
String t2 = new StringBuilder(s).reverse()
                                .toString();
System.out.println(t2);
avaJ
avaJ

The loop starts with i = s.length() - 1, that is, the last index, and decreases i by one as long as i >= 0. On each iteration s.charAt(i) is appended to the end of rev. Table 11.15 gives the four iterations.

Table 11.15: The trace table of the reversing loop. s = "Java".
ii >= 0s.charAt(i)rev (after the iteration)
3true'a'"a"
2true'v'"av"
1true'a'"ava"
0true'J'"avaJ"
−1false–the loop ends
0J1a2v3a▲ isrev"av" 0J1a2v3a▲ isrev"avaJ"
Figure 11.20: The reversing loop. Top: the i = 2 iteration, where 'v' has been appended and rev is “av”. Bottom: the i = 0 iteration, where 'J' has also been appended and the result is “avaJ”. s never changes.

Each rev += s.charAt(i) in the loop produces a new String; for a string of four characters this is negligible. The second way, new StringBuilder(s).reverse().toString(), is a single line. It creates a buffer with the contents of s, reverses the buffer and converts the result to a String. The two ways give the same output, and in both s does not change.

Both boundary cases of this loop work correctly. For the empty string, i starts at −1, the condition is false at the first check and rev stays empty. For a one-character string, the loop runs once and the string itself is obtained.

11.9.2A palindrome sentence

A word or sentence that reads the same backward as forward is called a palindrome: “kazak”, “ana”, “Ey Edip Adanada pide ye”. Because a sentence contains uppercase letters and spaces, a direct comparison gives a wrong result: 'E' and 'e' are different characters. The text is cleaned first, then compared from both ends inward.

String sentence = "Ey Edip Adanada pide ye";
Locale tr = Locale.forLanguageTag("tr");
String t = sentence.toLowerCase(tr).replace(" ", "");
int left = 0, right = t.length() - 1;
boolean isPal = true;
while (left < right && isPal) {
  if (t.charAt(left) != t.charAt(right))
    isPal = false;
  left++; right--;
}
System.out.println(isPal);
true
eyedipadanadapideye 19 9 9

The program works in these steps:

  1. toLowerCase(tr) lowercases all the letters with Turkish rules (tr is the Turkish Locale created on line 2), and replace(" ", "") removes the spaces. The 23-character sentence becomes the 19-character "eyedipadanadapideye".
  2. Two pointer variables are set up: left starts at 0 and right at the last index, 18. Until proven otherwise, isPal = true is assumed.
  3. On each iteration the characters at the two ends are compared. If they are not equal, isPal is made false and the loop condition ends the loop at the next check. If they are equal, the two pointers move one step inward.
  4. When the condition left < right becomes false, all the pairs have been checked.
Table 11.16: The trace table of the palindrome loop. t = "eyedipadanadapideye" (19 characters).
Iterationleftrightt.charAt(left)t.charAt(right)Equal?
1018eeyes
2117yyyes
3216eeyes
4315ddyes
5414iiyes
6513ppyes
7612aayes
8711ddyes
9810aayes
–99left < right is false: the loop ends, isPal = true
0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt 0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ leftrightt
Figure 11.21: The two pointers in the palindrome check. Top: the start, with left at 0 and right at 18. Bottom: the final state, where the pointers have met at the middle index 9. The middle 'n' is not compared with itself.

The second line of the program's output is a check line showing the variables after the loop: the cleaned text, its length 19 and the final values of the pointers, 9 and 9. Because the length is odd, a character with no partner is left in the middle. Nine iterations are enough: ⌊19 / 2⌋ = 9. The general rule is this: for a text of n characters, at most n/2 iterations are needed.

The same logic can be put into a method and tried on several sentences. In this version too the lowercasing is done with Turkish rules; this way sentences containing “I” and “İ” are processed correctly:

import java.util.Locale;

public class PalindromeTest {
    static boolean isPalindrome(String sentence) {
        String t = sentence.toLowerCase(Locale.forLanguageTag("tr")).replace(" ", "");
        int left = 0, right = t.length() - 1;
        boolean isPal = true;
        while (left < right && isPal) {
            if (t.charAt(left) != t.charAt(right))
                isPal = false;
            left++; right--;
        }
        return isPal;
    }

    public static void main(String[] args) {
        String[] sentences = {"Ey Edip Adanada pide ye", "Kaç kişi", "Ana", "Kazak", "Ali"};
        for (String c : sentences) {
            System.out.println(c + " -> " + isPalindrome(c));
        }
    }
}
Ey Edip Adanada pide ye -> true
Kaç kişi -> false
Ana -> true
Kazak -> true
Ali -> false

“Kaç kişi” is not a palindrome: its cleaned form is “kaçkişi” and its reverse is “işikçak”. In the first iteration 'k' meets 'i' and the loop ends there. “Ali” is also eliminated in the first iteration: 'a' ≠ 'i'.

11.9.3Counting vowels

A short way to tell whether a character belongs to a certain set is to gather the set in a string and search it with indexOf. If the character is in the set, indexOf returns 0 or a larger value; if not, −1.

Locale tr = Locale.forLanguageTag("tr");
String s = "Merhaba Dünya".toLowerCase(tr);
String vowels = "aeıioöuü";
int count = 0;
for (int i = 0; i < s.length(); i++) {
  char c = s.charAt(i);
  if (vowels.indexOf(c) >= 0) count++;
}
System.out.println(count);
5

“Merhaba Dünya” is lowercased first: “merhaba dünya”. The string vowels holds the eight vowels of Turkish: a, e, ı, i, o, ö, u, ü. The loop tries the thirteen characters in turn. Table 11.17 gives the result of indexOf for each character.

Table 11.17: The trace table of the vowel count. vowels = "aeıioöuü"; ␣ is a space.
icvowels.indexOf(c)Vowel?count
0m−1no0
1e1yes1
2r−1no1
3h−1no1
4a0yes2
5b−1no2
6a0yes3
7␣−1no3
8d−1no3
9ü7yes4
10n−1no4
11y−1no4
12a0yes5
0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓✓count4 0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓✓✓count5
Figure 11.22: The vowel scan. Top: i = 9, where 'ü' is found at index 7 of the string vowels and the counter becomes 4. Bottom: the scan has finished; the five marked cells (e, a, a, ü, a) are vowels.

The toLowerCase(tr) call at the start of the program is important here. Without the lowercasing, uppercase letters such as “A” and “E” could not be found in the string vowels. The parameterless toLowerCase() depends on the language of the machine: if the text has an uppercase “I” or “İ”, it may turn into the wrong lowercase letter on a non-Turkish machine. This is why Locale.forLanguageTag("tr") is given for Turkish text.

Example 11.8

What does the same program count for “Giresun Üniversitesi”? Which letters are counted?

Solution. The lowercased text is “giresun üniversitesi”. The vowels are, in order, i, e, u (giresun: three), ü, i, e, i, e, i (üniversitesi: six). The total is 3 + 6 = 9. For the space and the consonants indexOf returns −1 and the counter does not increase.

11.9.4Counting words

The number of words in a sentence cannot be found by counting the spaces and adding one. There can be several spaces at the start of the sentence, at the end, or between words. A more robust way is to count the transitions “from outside a word to inside a word”.

Definition 11.13

In this program, a word is an unbroken sequence of non-space characters. The number of words in a text equals the number of positions at which a non-space character is immediately preceded by a space or by the start of the text.

String text = "Ali  ata bak";
int word = 0;
boolean inWord = false;
for (int i = 0; i < text.length(); i++) {
  char c = text.charAt(i);
  if (c != ' ' && !inWord) {
    word++;
    inWord = true;
  } else if (c == ' ') inWord = false;
}
System.out.println(word);
3

The program keeps a boolean flag: inWord shows whether we are currently inside a word. When a non-space character arrives and the flag is false, a new word has begun: the counter increases and the flag is set to true. When a space arrives, the flag is set to false. If a non-space character arrives while the flag is already true, nothing is done; the same word continues.

Table 11.18: The trace table of the word-counting loop. text = "Ali␣␣ata␣bak" (12 characters).
icinWord (before)EventwordinWord (after)
0Afalsenew word1true
1ltruecontinues1true
2itruecontinues1true
3␣truethe word ends1false
4␣falsespace, not counted1false
5afalsenew word2true
6ttruecontinues2true
7atruecontinues2true
8␣truethe word ends2false
9bfalsenew word3true
10atruecontinues3true
11ktruecontinues3true
0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ new▲ newword3
Figure 11.23: The three word starts in the text “Ali␣␣ata␣bak”. The ▲ marks show the indices 0, 5 and 9, where the text goes from a space to a letter. The double space (indices 3 and 4) does not start a second word.

The same result can also be found with split in one line: text.trim().split("\\s+").length. trim() removes leading and trailing spaces; the pattern "\\s+" means “one or more whitespace characters” and counts consecutive spaces as a single delimiter. This shortcut has a trap: for an empty text or one made only of spaces, the result is 1, not 0. "".split(...) returns an array with one part, and that part is the empty string. The program below compares the three methods on five texts:

public class WordShortcut {
    public static void main(String[] args) {
        String[] texts = {"Ali  ata bak", "  Ali ata  bak ", "", "   ", "tek"};
        for (String text : texts) {
            int k1 = text.trim().split("\\s+").length;
            int k2 = text.isBlank() ? 0 : text.trim().split("\\s+").length;
            System.out.println("[" + text + "] " + k1 + " " + k2 + " " + text.split(" ").length);
        }
    }
}
[Ali  ata bak] 3 3 4
[  Ali ata  bak ] 3 3 6
[] 1 0 1
[   ] 1 0 0
[tek] 1 1 1

Each line prints, in order, the result of the shortcut, the result with the isBlank() check and the result of split(" "). The first two columns are the same except for the empty texts. split(" "), however, counts every single space as a delimiter and so produces empty parts for double spaces: for “Ali␣␣ata␣bak” it gives 4 instead of 3. This is why the shortcut is used after checking with isBlank() first.

11.9.5Character frequency

To count how many times each letter occurs in a text, an int array of 26 cells is used. Cell 0 is the counter for the letter 'a', cell 1 for 'b' and cell 25 for 'z'. The cell of a letter is found with c - 'a', taking advantage of the fact that chars are numbers.

String s = "kavak";
int[] freq = new int[26];
for (int i = 0; i < s.length(); i++) {
  char c = s.charAt(i);
  if (c < 'a' || c > 'z') continue;
  freq[c - 'a']++;
}
for (int k = 0; k < 26; k++)
  if (freq[k] > 0)
    System.out.println((char) ('a' + k)
                       + ": " + freq[k]);
a: 2
k: 2
v: 1
Table 11.19: How the frequency array is updated for “kavak”. Only the cells that change are shown.
icc − 'a'Cell updatedfreq[0]freq[10]freq[21]
0k107 − 97 = 10freq[10]010
1a97 − 97 = 0freq[0]110
2v118 − 97 = 21freq[21]111
3a97 − 97 = 0freq[0]211
4k107 − 97 = 10freq[10]221
skavaka2b0c0d0e0f0g0h0i0j0k2l0m0n0o0p0q0r0s0t0u0v1w0x0y0z0freq[0] = 'a' … freq[25] = 'z'
Figure 11.24: The 26-cell frequency array after “kavak” has been scanned. Only the cells for 'a' (2), 'k' (2) and 'v' (1) are nonzero.

The second loop goes through the 26 cells in order and prints only those greater than zero. To get from a cell number back to a letter, (char) ('a' + k) is written: 'a' + 10 = 97 + 10 = 107, that is, 'k'. The cast ((char)) is needed; otherwise 'a' + k would be an int and 107 would be printed. That the output is in alphabetical order also comes from this second loop: the cells are visited from 0 to 25.

The two costs of the program can be computed separately. The first loop scans a text of n characters once; the second loop always runs 26 iterations. The total work is proportional to n + 26. A solution that scans the text from the start for each letter would make 26 · n comparisons.

Common mistake

Skipping the range check on line 5. The 26-cell table is only for lowercase English letters. If the program is run without the check on a text containing uppercase letters, spaces or Turkish letters, then, for example for 'ç', 'ç' − 'a' = 231 − 97 = 134 comes out and the bound of the array is exceeded:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 134 out of bounds for length 26

The check skips characters outside a–z with continue. If uppercase letters are to be counted, they are lowercased first. For Turkish letters, either an alphabet string of 29 letters and indexOf are used, or a wider table is built.

11.9.6The Caesar cipher

The Caesar cipher is a very old encryption method that shifts every letter forward by a fixed number of positions in the alphabet. If the shift is 3, 'a' → 'd' and 'b' → 'e'. The letters at the end of the alphabet wrap around to the start: 'x' → 'a', 'y' → 'b', 'z' → 'c'.

The arithmetic of wrapping around is the mod operation. The place of a letter in the alphabet is converted to a number from 0 to 25 with c - 'a'. The shift is added and the remainder of the result divided by 26 is taken:

pos = (c − 'a' + shift) % 26

The remainder is always between 0 and 25; so the result does not spill outside the alphabet. Then 'a' + pos turns it back into a letter. The program encrypts only lowercase English letters (a–z); spaces, digits, uppercase and Turkish letters are appended unchanged by the check on line 6.

String text = "yazilim";
int shift = 3;
StringBuilder enc = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
  char c = text.charAt(i);
  if (c < 'a' || c > 'z') { enc.append(c); continue; }
  int pos = (c - 'a' + shift) % 26;
  char out = (char) ('a' + pos);
  enc.append(out);
}
System.out.println(enc);
bdclolp
Table 11.20: Encrypting the word “yazilim” with a shift of 3.
icc − 'a'(c − 'a' + 3) % 26newenc
0y2427 % 26 = 1bb
1a03 % 26 = 3dbd
2z2528 % 26 = 2cbdc
3i811 % 26 = 11lbdcl
4l1114 % 26 = 14obdclo
5i811 % 26 = 11lbdclol
6m1215 % 26 = 15pbdclolp
textenc0y1a2z3i4l5i6mbdc+3a b c … x y zy + 3 → b (wraps around)
Figure 11.25: Encrypting the letter 'z'. 25 + 3 = 28 is outside the alphabet; 28 % 26 = 2 wraps around and 'c' is obtained. In the enc buffer “bdc” has accumulated so far.

To decrypt, the letters are shifted back by the same amount. But writing (c - 'a' - 3) % 26 is dangerous: in Java the remainder of a negative number is negative, and (0 − 3) % 26 = −3. Instead of shifting back, a forward shift of 26 − 3 = 23 is made; going 23 forward in the alphabet is the same as going 3 back, and the result always stays positive. The program below puts the encryption into a method and decrypts with the same method:

public class CaesarDecrypt {
    static String shift(String text, int shift) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c < 'a' || c > 'z') { result.append(c); continue; }
            int pos = (c - 'a' + shift) % 26;
            result.append((char) ('a' + pos));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String enc = shift("yazilim", 3);
        System.out.println(enc);
        System.out.println(shift(enc, 26 - 3));
        System.out.println(shift("kaz", 2));
        System.out.println((-3) % 26);
    }
}
bdclolp
yazilim
mcb
-3

The second line is the decrypted text: “yazilim”. The third line is the encryption of the word “kaz” with a shift of 2: 'k' (10) → 12 → 'm', 'a' → 'c', 'z' (25) → 27 % 26 = 1 → 'b'. The last line confirms the value of a negative remainder in Java. The Caesar cipher has only 25 meaningful keys; a computer tries them all at once. This is why the method is used not for security but to teach modular arithmetic and character processing.

11.9.7Worked examples from the exercises

Six of the exercises in the slides are solved below. Each solution uses one or more of the tools described in the notes.

Example 11.9

A program that finds separately the numbers of uppercase letters, lowercase letters, digits and spaces in a sentence.

Solution. Each character is classified with an else-if chain. The methods isUpperCase, isLowerCase and isDigit of the Character class also recognize Turkish letters; so “Ö” counts as uppercase and “ı” as lowercase.

public class CharTypes {
    public static void main(String[] args) {
        String sentence = "Giresun 2024 Yılı Öğrenci";
        int upper = 0, lower = 0, digit = 0, space = 0, other = 0;
        for (int i = 0; i < sentence.length(); i++) {
            char c = sentence.charAt(i);
            if (Character.isUpperCase(c)) upper++;
            else if (Character.isLowerCase(c)) lower++;
            else if (Character.isDigit(c)) digit++;
            else if (c == ' ') space++;
            else other++;
        }
        System.out.println("Upper: " + upper + ", lower: " + lower + ", digit: " + digit
                + ", space: " + space + ", other: " + other);
    }
}
Upper: 3, lower: 15, digit: 4, space: 3, other: 0

In the sentence “Giresun 2024 Yılı Öğrenci”, G, Y and Ö are uppercase. The lowercase letters are “iresun” (6), “ılı” (3) and “ğrenci” (6): 15 in total. There are four digits and three spaces. The total 3 + 15 + 4 + 3 = 25 equals the length of the sentence.

Example 11.10

A program that checks with character frequencies whether two words are anagrams (a rearrangement of the same letters, e.g. “elma” – “alem”).

Solution. If the lengths differ, the words cannot be anagrams. If the lengths are the same, a single frequency array is enough: the letters of the first word increase the counters and those of the second decrease them. If all the cells are zero in the end, the two words have the same letters in the same numbers.

public class Anagram {
    static boolean isAnagram(String a, String b) {
        if (a.length() != b.length()) return false;
        int[] freq = new int[26];
        for (int i = 0; i < a.length(); i++) {
            freq[a.charAt(i) - 'a']++;
            freq[b.charAt(i) - 'a']--;
        }
        for (int k = 0; k < 26; k++)
            if (freq[k] != 0) return false;
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("elma", "alem"));
        System.out.println(isAnagram("kavak", "kavka"));
        System.out.println(isAnagram("kalem", "kelam"));
        System.out.println(isAnagram("kitap", "katip"));
        System.out.println(isAnagram("ders", "dere"));
    }
}
true
true
true
true
false

“ders” and “dere” have the same length, but the 's' cell is left at +1 and the 'e' cell at −1; the result is false. The program is written only for lowercase English letters; the warning in the frequency section applies here too for Turkish letters.

Example 11.11

A program that prints the full name entered by the user in the form “SURNAME, First”, with the surname in uppercase.

Solution. The line is read with nextLine(), because the full name contains spaces. For people with several first names, the surname is taken to be the last word and is separated with lastIndexOf(' '). The conversion to uppercase is done with Turkish rules.

import java.util.Locale;
import java.util.Scanner;

public class FullName {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String line = in.nextLine().strip();
        int space = line.lastIndexOf(' ');
        String first = line.substring(0, space).strip();
        String last = line.substring(space + 1);
        System.out.println(last.toUpperCase(Locale.forLanguageTag("tr")) + ", " + first);
    }
}

When “Ada Nur Yılmaz” is entered, the output is:

YILMAZ, Ada Nur

When “␣␣Mehmet Işık␣” is entered, strip() removes the margin spaces and the output is:

IŞIK, Mehmet

The uppercase form of “Işık” under Turkish rules is “IŞIK”. The program fails on a single-word input because lastIndexOf returns −1; this case can be checked separately.

Example 11.12

A program that finds the longest word in a sentence with split.

Solution. The sentence is split into words with the pattern "\\s+". The first candidate is the first word; each word is compared with the candidate and, if longer, becomes the new candidate.

public class LongestWord {
    public static void main(String[] args) {
        String sentence = "Bilgisayar mühendisliği  öğrencileri dizgileri seviyor";
        String[] words = sentence.trim().split("\\s+");
        String longest = words[0];
        for (String k : words) {
            if (k.length() > longest.length()) longest = k;
        }
        System.out.println(longest + " " + longest.length() + " " + words.length);
    }
}
mühendisliği 12 5

Although the sentence has a double space, five words are found. “mühendisliği” is the longest with 12 characters. “öğrencileri” has 11 characters. Because the condition is >, if two words have the same length the one that comes first is kept.

Example 11.13

A program that extends the Caesar cipher to support uppercase letters (A–Z) too and leaves other characters as they are.

Solution. Each character falls into one of three groups. Lowercase letters are shifted relative to 'a' and uppercase letters relative to 'A'. Digits, spaces and punctuation are appended unchanged.

public class CaesarUpper {
    static String encrypt(String text, int shift) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c >= 'a' && c <= 'z') {
                result.append((char) ('a' + (c - 'a' + shift) % 26));
            } else if (c >= 'A' && c <= 'Z') {
                result.append((char) ('A' + (c - 'A' + shift) % 26));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String s = encrypt("Merhaba, Dunya XYZ!", 3);
        System.out.println(s);
        System.out.println(encrypt(s, 26 - 3));
    }
}
Phukded, Gxqbd ABC!
Merhaba, Dunya XYZ!

'M' → 'P', 'X' → 'A', 'Y' → 'B', 'Z' → 'C'; the comma, space and exclamation mark stay as they are. The second line shows that a shift of 23 turns the text back. In this program Turkish letters fall into the “other characters” group and are not encrypted; this is why “Dunya” is used in the sample text instead of “Dünya”.

Example 11.14

A program that deletes all the spaces in a string with StringBuilder, without using replace.

Solution. The string is scanned and every non-space character is appended to the buffer. Spaces are skipped.

public class RemoveSpaces {
    public static void main(String[] args) {
        String s = " Ey Edip  Adanada pide ye ";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c != ' ') sb.append(c);
        }
        System.out.println("[" + sb + "] " + sb.length() + " " + s.length());
    }
}
[EyEdipAdanadapideye] 19 26

The 26-character text has seven spaces: the one at the start, the one at the end, the double space after “Edip” and three single spaces. 19 characters remain. This number is the same as the length of the cleaned text in the palindrome example; apart from letter case, the result is the same too.

11.10Formatting with printf

When a report or a table is printed, we want the values to stay aligned and decimal numbers to be cut at a certain number of digits. Concatenation with + does not provide this easily. The System.out.printf method, however, formats text according to a pattern.

Definition 11.14

The first parameter of printf is the format string. Plain text in the format string is written as it is. Each format specifier that begins with % stands in for the next argument and says how it is to be written. The general structure of a specifier is %[-][width][.precision]type. The main types are s (text), d (integer), f (floating-point number) and n (line end).

String name = "Java"; int qty = 3; double price = 17.5;
System.out.printf("%-8s %3d %7.2f%n", name, qty, price);
Java       3   17.50
[Java    ][  3][  17.50]
[    Java][3  ][17.5][1.750000e+01]
[Giresun][12345][3][4]
true c 50%

The first printf line of the program is the example from the slides. The three specifiers are matched with the three arguments in order. Figure 11.26 shows how the output is built cell by cell.

%-8s␣%3d␣%7.2f%nformat stringargumentsname"Java"qty3price17.5output:Java␣␣␣␣␣␣␣3␣␣␣17.50⏎line end
Figure 11.26: The format string "%-8s %3d %7.2f%n". “Java” is left-aligned in 8 cells and completed with four spaces. Then comes the plain space in the format string. The number 3 is right-aligned in 3 cells. 17.5 becomes “17.50” with two decimals and is right-aligned in 7 cells. %n ends the line.
  • %-8s: the text is written in a field of at least 8 characters. The minus sign left-aligns it; since “Java” has four characters, four spaces are added to its right.
  • %3d: the integer is right-aligned in a field of 3 characters; two spaces come before the 3.
  • %7.2f: the number is written with two digits after the decimal point (“17.50”, five characters) and right-aligned in a field of 7 characters; two spaces come before it.
  • %n: adds the line end appropriate to the operating system.

The following lines of the program make the limits of the fields visible with square brackets and try other formats. %8s right-aligns because there is no minus sign. %-3d left-aligns. %.1f writes one decimal without giving a width. %e is scientific notation: 1.75 × 10¹. The fourth line shows two important rules. First, the width is a lower bound: since “Giresun” has 7 characters, %3s does not cut it and writes all of it. Second, %.0f rounds halves up: 2.5 → 3 and 3.5 → 4. On the last line you can see that %s also writes boolean and char values. %% is the percent sign itself.

Format specifiers are ideal for tables. When fields of the same width are written one below the other, the columns line up on their own:

public class Table {
    public static void main(String[] args) {
        String[] product = {"Pen", "Notebook", "Calculator"};
        int[] qty = {12, 3, 1};
        double[] price = {7.5, 42.0, 349.9};
        System.out.printf("%-15s %5s %9s%n", "Product", "Qty", "Amount");
        for (int i = 0; i < product.length; i++) {
            System.out.printf("%-15s %5d %9.2f%n", product[i], qty[i], qty[i] * price[i]);
        }
    }
}
Product           Qty    Amount
Pen                12     90.00
Notebook            3    126.00
Calculator          1    349.90

Because the header line and the data lines use the same widths (15, 5, 9), the columns stand in neat order. The text column is left-aligned and the number columns right-aligned; this is the usual arrangement in tables. In the amount column, 12 × 7.5 = 90, 3 × 42 = 126 and 1 × 349.9 = 349.9 are written with two decimals.

The decimal separator depends on the locale. The same program writes the following on a machine with a Turkish setting:

Product           Qty    Amount
Pen                12     90,00
Notebook            3    126,00
Calculator          1    349,90

The number itself does not change; only the way it is written does. The example in the slides also writes “17,50” on a Turkish machine. If the same output is wanted on every machine, the locale is given in the first parameter, as in printf(Locale.US, …).

The compiler does not check the format string. If a specifier and the type of its argument do not match, or an argument is missing, the error appears while the program runs:

public class FormatError {
    public static void main(String[] args) {
        System.out.printf("%d%n", 3.5);
    }
}
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double

%d expects an integer, but 3.5 is a double. The message says that the d conversion cannot be used with Double. Java does not round or cut the number; it throws an exception. A similar exception occurs for a missing argument; the program stops after the first specifier has been written:

public class FormatMissing {
    public static void main(String[] args) {
        System.out.printf("%s and %s%n", "Ada");
    }
}
Ada and
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s'
Common mistake

Printing a decimal value with %d or an integer with %f. Both throw an IllegalFormatConversionException. %d is used for int and %f for double; the safe choice for any type is %s, but it too provides no format checking. Forgetting the line end is also common: printf does not move to the next line by itself like println; %n is needed.

11.11Unicode and text length

Java's char type is 16 bits and can take 65,536 different values. Almost all the characters of everyday texts, Turkish letters included, are in this range. But the Unicode standard today defines more than 150 thousand characters: old writing systems, mathematical symbols, emojis. Some of these do not fit in a single char.

Definition 11.15

In Unicode every character has a number; this number is called a code point. Java strings store these numbers with the UTF-16 encoding, in 16-bit code units. A char is one code unit. Code points greater than U+FFFF are stored as a pair made up of two code units. length() gives the number of code units, not the number of characters.

"çay".length() = 3çayan emoji (e.g. a smiling face): length() = 2← 1 visible characterD83DDE00← 2 chars (a UTF-16 pair)
Figure 11.27: “çay” consists of three code units and its length is 3; the ç fits in a single char. The smiling-face emoji is a single visible character but is stored as a UTF-16 pair made up of two code units named D83D and DE00; its length is 2.
public class UnicodeDemo {
    public static void main(String[] args) {
        String tea = "çay";
        String emoji = "😀";
        System.out.println(tea.length() + " " + emoji.length() + " " + emoji.codePointCount(0, emoji.length()));
        System.out.printf("%X %X %X%n", (int) emoji.charAt(0), (int) emoji.charAt(1), emoji.codePointAt(0));
        String combined = "çay";
        System.out.println(combined.length() + " " + combined.equals(tea));
        System.out.println(java.text.Normalizer.normalize(combined, java.text.Normalizer.Form.NFC).equals(tea));
        System.out.println("straße".toUpperCase(java.util.Locale.ROOT) + " " + "straße".length() + " " + "straße".toUpperCase(java.util.Locale.ROOT).length());
    }
}
3 2 1
D83D DE00 1F600
4 false
true
STRASSE 6 7

In the first line the length of “çay” is 3 and the length of the emoji is 2. codePointCount, however, counts code points and gives 1 for the emoji. The second line prints the two code units of the emoji and its real code point in hexadecimal: U+1F600. Because this number is greater than 65,535, it does not fit in a single char.

The third line shows a subtler case. The letter “ç” can be written in two ways in Unicode: as a single ready-made character (U+00E7) or as a “c” plus a separate cedilla mark added beneath it (U+0327). The second form looks the same on the screen but has length 4 and is not equal to the first form under equals. The java.text.Normalizer class brings the two forms to the same representation; the fourth line shows that equality holds after normalization. On the last line, when the German letter “ß” is converted to uppercase it turns into two letters, “SS”, and the string grows longer: the 6-character “straße” becomes the 7-character “STRASSE”.

The consequence of these details for everyday programs is this: in Turkish texts length() and charAt work as expected. In texts containing emojis, combining marks or other writing systems, however, the “number of characters the user sees” can differ from length(). In such texts, operations such as reversing can also split a pair in the middle and produce broken characters.

11.12Summary

  • char holds a single character in single quotes ('T'), and String holds a sequence of characters in double quotes ("Tarkan"). String is not a primitive type but a class in the java.lang package; the variable holds the reference to the object. "" is a real object of length 0; null points to no object, and if a method is called through it, a NullPointerException occurs.
  • + is concatenation if one of the operands is a string and addition if both are numbers, and it is evaluated from left to right: "12" + 3 + 4 = "1234", 3 + 4 + "12" = "712". A char is a number: 'a' + 1 = 98, 'k' − 'a' = 10.
  • String is immutable. toUpperCase, replace, substring and + return a new object; if the result is not assigned, it is lost. What changes is not the object but the place the variable points to. Objects that nobody points to are cleaned up by the garbage collector.
  • Indices run from 0 to length() − 1; an out-of-bounds index gives a StringIndexOutOfBoundsException. length() is a method for strings, while length is a field for arrays.
  • substring(a, b): a included, b excluded; length b − a; valid range 0 ≤ a ≤ b ≤ length(). indexOf gives the first position or −1. split takes a regular expression; consecutive delimiters produce empty parts, and trailing empty parts are dropped.
  • replace searches for plain text and replaceAll for a regular expression. trim removes only ASCII whitespace, while strip removes all Unicode whitespace. format and printf depend on the locale.
  • == compares references and equals compares contents; strings are always compared with equals. compareTo gives the code difference of the first differing character, or the length difference if there is none. Uppercase letters come before lowercase ones and English letters before Turkish ones; for Turkish sorting, Collator is used.
  • In Turkish, i ↔ İ and ı ↔ I are paired. The parameterless toLowerCase()/toUpperCase() depend on the language of the machine; Locale.ENGLISH is given for technical text and Locale.forLanguageTag("tr") for Turkish text.
  • The same constants share a single object in the string pool; new always creates a new object. Constant expressions are concatenated at compile time and enter the pool; a concatenation with a variable produces a new object. intern() gives the object in the pool. "constant".equals(x) is safe against null.
  • next() reads a word and leaves the ⏎ in the buffer; nextLine() reads the rest of the line and consumes the ⏎. If a line is to be read after next() or nextInt(), a nextLine() is put in between.
  • In a loop, s = s + x produces a new object on every iteration; in n iterations about n²/2 characters are copied. StringBuilder is a mutable buffer: append, insert and reverse change the same object; the result is obtained with toString().
  • The common pattern of the applications is a scan of characters. Reversing scans from the end to the start, and the palindrome check scans from both ends inward. Word counting uses a flag. A frequency table selects the cell with c - 'a'; the Caesar cipher shifts with (c - 'a' + k) % 26.
  • In printf, %-8s left-aligns and %3d right-aligns; %7.2f writes with two decimals in 7 cells; %n is the line end. A type mismatch gives an exception at run time.
  • Strings are made up of UTF-16 code units; Turkish letters fit in a single char, while characters such as emojis take two chars. So length() is not always the same as the number of visible characters.

11.13Key terms

These are the key terms introduced in this chapter.

  • string
  • character
  • string literal
  • primitive type
  • object
  • reference
  • heap
  • string concatenation
  • immutable
  • immutability
  • garbage collector
  • index
  • indexing
  • out of bounds
  • substring
  • delimiter
  • regular expression
  • whitespace
  • content vs reference comparison
  • lexicographic order
  • uppercase / lowercase
  • locale
  • string pool
  • buffer
  • mutable
  • reversing
  • Caesar cipher
  • formatting
  • format string
  • format specifier
  • code point
  • code unit
  • exception

11.14Test Yourself

  1. With int p = 2, q = 5;, what does the line System.out.println(p + q + "x" + p + q); print?

    Answer

    + is evaluated from left to right. The first two operands are numbers: 2 + 5 = 7. Then 7 + "x" = "7x", and the expression turns into concatenation: "7x2", then "7x25". The output is 7x25.

  2. After the lines String s = "dizgi"; s.toUpperCase(); s = s.replace('i', 'ı');, what does s point to?

    Answer

    The result of toUpperCase() is lost because it is not assigned; s is still "dizgi". The result of replace, however, is assigned and both 'i's become 'ı': s points to "dızgı". The "dizgi" object has not changed; only the arrow of s has moved to the new object.

  3. For String t = "Karadeniz";, what are the values of t.length(), t.charAt(4), t.indexOf("de"), t.substring(4, 8) and t.lastIndexOf('a')?

    Answer

    The indices: K=0, a=1, r=2, a=3, d=4, e=5, n=6, i=7, z=8. The length is 9. charAt(4) is 'd'. "de" starts at index 4. substring(4, 8) takes indices 4–7: "deni" (length 8 − 4 = 4). The last 'a' is at index 3.

  4. What is "x;;y;z;;".split(";").length? What are the parts?

    Answer

    The text is cut at every semicolon: "x", "", "y", "z", "", "". The empty part between two consecutive semicolons stays; the two trailing empty parts are dropped. The result is [x, , y, z], with length 4.

  5. What are the values of "Masa".compareTo("masa"), "kitap".compareTo("kitaplık") and "ödev".compareTo("sınav")? Which of them contradict true dictionary order?

    Answer

    In the first, the first characters are 'M' (77) and 'm' (109): 77 − 109 = −32. In the second, "kitap" is the beginning of "kitaplık": 5 − 8 = −3. In the third, 'ö' (246) meets 's' (115): 246 − 115 = 131, so "ödev" comes after "sınav". Because ö comes before s in the Turkish alphabet, the third result contradicts dictionary order.

  6. On a computer with a Turkish setting, what is the value of the expression "MAIL".toLowerCase().equals("mail")? How is the expression fixed?

    Answer

    The parameterless toLowerCase() uses Turkish rules and converts "I" to "ı": "maıl". Because it is not equal to "mail", the value is false. Since "MAIL" is a technical word, toLowerCase(Locale.ENGLISH) is written, or "MAIL".equalsIgnoreCase("mail") is used directly; both give true.

  7. After the lines String a = "ab"; String b = "a"; String c = b + "b"; final String d = "a"; String e = d + "b";, what are the values of a == c, a == e and a == c.intern()?

    Answer

    Because b is not final, b + "b" produces a new object at run time: a == c is false. Because d is a final constant, d + "b" becomes the constant "ab" at compile time and comes from the pool: a == e is true. c.intern() returns the "ab" in the pool: true.

  8. The user types “42⏎” first, then “Ali Can⏎”. After the lines int n = in.nextInt(); String s = in.nextLine(); String t = in.next();, what are s and t?

    Answer

    nextInt() reads 42 and leaves the ⏎. nextLine() reads up to that ⏎: s is the empty string. next() reads the first word of the second line: t is "Ali". " Can⏎" stays in the buffer.

  9. The word “ankara” is encrypted with a Caesar cipher with a shift of 4. What is the result? What shift is used to decrypt?

    Answer

    The places of the letters: a=0, n=13, k=10, r=17. Adding 4 gives 4, 17, 14, 21; none exceeds 26. The six letters turn, in order, into e, r, o, e, v, e: "eroeve". To decrypt, a shift of 26 − 4 = 22 is used.

  10. What does the line System.out.printf("[%6.1f][%-4s][%03d]%n", 2.75, "ab", 7); print?

    Answer

    %6.1f rounds 2.75 to one decimal: "2.8" (three characters) and right-aligns it in 6 cells; three spaces come before it. %-4s left-aligns "ab" in 4 cells; two spaces come after it. %03d pads 7 with zeros to 3 cells: "007". The output is [ 2.8][ab ][007] (with the English locale; “2,8” with the Turkish one).

11.15Further reading

  • Oracle, The Java Tutorials, the pages “Strings” and “The StringBuilder Class”: creating strings, concatenation, methods and StringBuilder are explained with official examples.
  • Oracle, Java SE 21 API Documentation, the classes java.lang.String, java.util.Formatter and java.util.Locale: the exact behavior of each method, the empty-part rules of split and the full list of format specifiers.
  • R. Sedgewick and K. Wayne, Computer Science: An Interdisciplinary Approach (Addison-Wesley, 2016), Section 3.1 “Using Data Types”: String is treated as a data type; search examples on genome strings are given.
  • Unicode Consortium, The Unicode Standard, the “Case Mappings” section and the file SpecialCasing.txt: the source of the Turkish and Azeri i/İ/ı/I rules and of length-changing conversions such as “ß → SS”.

11.16References

  1. P. Deitel, H. Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
  2. Y. D. Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
  3. Oracle, The Java Tutorials: Strings; The StringBuilder Class.
  4. Oracle, Java SE 21 API: String, StringBuilder.
  5. R. Sedgewick, K. Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 3.1 Using Data Types.
  6. Unicode Consortium, The Unicode Standard.

Related pages: Chapter 11 slides · Study questions · String Lab simulator · Glossary · © Sercan Külcü. All rights reserved.