Chapter 11: Strings
Introduction
Learning Outcomes
Explain the difference between String and char.
Use indices and the basic methods.
Tell content comparison from reference comparison.
Produce formatted text with printf.
Basics
What Is a String?
Stringis ajava.langclass that represents a sequence of characters (no import needed).- String literals use double quotes (
"Tarkan"), acharuses single quotes ('T'). Stringis not a primitive type but an immutable object; the variable holds a reference to it.
Basics
Creating Strings
String name = "Tarkan"; String empty = ""; String copy = new String(name); String none = null;
- A string literal is usually preferred over
new. ""is a real object of length 0;nullrefers to no object at all (none.length()→NullPointerException).
Basics
Immutability
- Once created, a String's contents never change.
- Concatenation and conversion produce a new String; the old object stays as it was.
- To use the result, assign the returned value to a variable.
- An object no variable refers to is reclaimed by the garbage collector.
String s = "Merhaba";
s = s + "!"; → a new object; the arrow moves to it, the old object is unchanged.
Basics · Step through the code
Immutability: toUpperCase()
lang refers to the "java" object in the pool.
toUpperCase() produces a new "JAVA" object, but the result is assigned to nothing → it is lost. lang still refers to the old object.
The old object is unchanged, so it prints java.
This time the returned object is assigned to lang: the arrow moves to it. The "java" object is still intact.
It prints JAVA. What changed is not the object but where the variable points.
String lang = "java"; lang.toUpperCase(); System.out.println(lang); // java lang = lang.toUpperCase(); System.out.println(lang); // JAVA
Index
Indexing
- The first character is at index 0, the last at length() − 1;
length()is a method (unlike thelengthfield of arrays). charAt(i)returns thecharat that position;charAt(7)→StringIndexOutOfBoundsException.
Methods · Step through the code
Basic Methods
A 16-character string (the space is a character too: index 4).
length() → 16; indices 0 … 15.
indexOf gives the index of the first character of the match → 5 (−1 if absent).
substring(5, 16): 5 included, 16 excluded → 11 characters: "Programlama".
contains("Java") → true. No method changed s.
The results are joined and printed.
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);
Methods
Common String Methods
| Method | Result |
|---|---|
| length() | Number of chars (code units) |
| charAt(i) | The char at position i |
| substring(a,b) | Substring from a (incl.) to b (excl.) |
| indexOf(x) | First position or -1 |
| toLowerCase() | New lowercase String |
| trim() / strip() | New String without leading/trailing spaces |
Methods · Step through the code
split and replace Step by Step
split(",") cuts the text at the commas: "a", "b", "", "c". Between two adjacent commas is an empty string, and it stays in the array.
Arrays.toString(p) → [a, b, , c], p.length → 4. (Empty parts at the end are dropped: "a,b,,".split(",") gives only 2 parts.)
s = "ali veli": 8 characters, a space at index 3.
replace('l', 'L') turns every 'l' into 'L' (indices 1 and 6) and returns a new String; s is unchanged on this line.
t is printed: aLi veLi.
s is still ali veli: Strings are immutable, so the result exists only in the returned value.
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 veliMethods
replace, replaceAll, join, valueOf, format
| Call | Result |
|---|---|
"banana".replace('a', 'o') | bonono |
"banana".replace("an", "AN") | bANANa |
"a1b22c333".replaceAll("[0-9]+", "#") | a#b#c# |
"a1b22c333".replaceFirst("[0-9]+", "#") | a#b22c333 |
"Ada Can Ece".replaceAll(" +", " ") | Ada Can Ece |
String.join(", ", "Ada", "Can", "Ece") | Ada, Can, Ece |
String.valueOf(3.5) / String.valueOf(new char[]{'h','i'}) | 3.5 / hi |
String.format(Locale.US, "%.2f", 3.14159) | 3.14 |
String.format(Locale.US, "%5d|%-5d|%05d", 42, 42, 42) | 42|42 |00042 |
String.format(Locale.US, "%,d", 1234567) | 1,234,567 |
replace searches for plain text, replaceAll for a regular expression; all return a new String. Without a locale, %.2f prints 3,14 on a computer set to Turkish.
Methods
Substring Bounds: s = "PROGRAM"
Think of indices as the lines between characters: between 0 and 3 is "PRO". Length = 3 − 0.
The end may be length() = 7: the last character is included.
One-parameter version: from the start to the end.
Start = end → the empty string "" (not an error).
End > length() or start > end → run-time error.
substring(a, b): a included, b excluded; the result has length b − a.- Valid range: 0 ≤ a ≤ b ≤ length().
Methods · Step through the code
Application: Splitting an Email Address
An 11-character email address; we will separate the user name and the domain.
indexOf('@') → 3: the separator's position.
substring(0, 3): 0 included, 3 (@) excluded → "ali".
substring(4): from the character after @ to the end → "gru.edu".
charAt(0) returns a char: 'a' (single quotes).
The parts are joined and printed.
Character.toUpperCase converts a char to uppercase → A. email never changed.
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));
Comparison · Step through the code
== vs. equals
The literal "Giresun" goes into the string pool; a refers to it.
new String(...) creates a separate object on the heap, even with the same contents.
The same literal again: the existing object in the pool is shared → c carries the same arrow as a.
a == b: the two arrows point to different objects → false (contents are ignored).
a == c: the two arrows point to the same object → true.
equals compares character by character: G=G, i=i, … → true. Always use equals for contents.
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
Comparison
Comparison Methods
| Method | Purpose | Example |
|---|---|---|
equals | Content equality | "abc".equals("abc") → true |
equalsIgnoreCase | Equality ignoring case | "Java".equalsIgnoreCase("JAVA") → true |
startsWith | Starts with given text | "Giresun".startsWith("Gir") → true |
endsWith | Ends with given text | "Giresun".endsWith("sun") → true |
compareTo | Lexicographic order: <0, 0, >0 | "elma".compareTo("armut") → positive |
compareTo works on Unicode values: uppercase letters come before lowercase, and Turkish letters (ç, ğ, ı, ö, ş, ü) may not follow alphabetical order.
Comparison · Step through the code
compareTo: Character and Length Differences
First x = "elma" (4 characters). The comparison uses the Unicode codes of these characters.
y = "armut" (5 characters). The next line computes x.compareTo(y).
The first difference is at position 0: 'e' - 'a' = 101 - 97 = 4. Positive: "elma" comes after "armut" in the dictionary.
k = "kedi" (4 characters). Now let's see what happens when one string is a prefix of the other.
k.compareTo("kediler"): the first 4 characters are the same and "kedi" ends; the result is the length difference.
4 - 7 = -3: the shorter "kedi" comes first. Rule: the character difference if one exists, otherwise the length difference.
String x = "elma"; String y = "armut"; System.out.println(x.compareTo(y)); // 4 String k = "kedi"; System.out.println(k.compareTo("kediler")); // -3
Comparison
Turkish Characters and Locale
| Call (tr = Locale.forLanguageTag("tr")) | Result |
|---|---|
"TITLE".toLowerCase(Locale.ENGLISH) | title |
"TITLE".toLowerCase(Locale.forLanguageTag("tr")) | tıtle |
"i".toUpperCase(tr) | İ |
"i".toUpperCase(Locale.ENGLISH) | I |
"I".toLowerCase(tr) | ı |
"ISPARTA".toLowerCase(tr) | ısparta |
"ısparta".toUpperCase(tr) | ISPARTA |
- A plain
toLowerCase()depends on the machine's default locale: the same code may give a different result on another computer. - Pass
Locale.ENGLISHfor technical text such as keywords or file extensions, andLocale.forLanguageTag("tr")for Turkish text. "TITLE".toLowerCase(tr).equals("title")→false;"title".equalsIgnoreCase("TITLE")→true.
Memory
The String Pool
- Identical string literals share a single object in the pool (saves memory; safe thanks to immutability).
new String(...)always creates a separate object.- You can't always tell from the code whether a String came from the pool, so compare contents with
equals, not==.
Memory
Constant Folding and intern
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
The compiler joins constant expressions ("a" + "b", a final variable); the result is the pooled "ab". a + b creates a new object at run time; intern() returns the pooled object.
With String x = null;, "text".equals(x) → false, but x.equals("text") → NullPointerException. So put the literal on the left.
Input
Reading Text with Scanner
import java.util.Scanner; // ... Scanner in = new Scanner(System.in); String word = in.next(); in.nextLine(); String line = in.nextLine();
next()reads one word: it skips leading spaces and stops at the first space or line end.nextLine()reads everything up to the line end (⏎) and consumes the ⏎.- After
next()ornextInt(), the ⏎ left in the buffer must be consumed by a separatenextLine().
Input · Step through the code
Code Trace: next() and nextLine()
The Scanner attaches to the keyboard stream; the buffer is empty for now.
next() finds nothing to read and waits. The user types Ada and presses Enter → "Ada⏎" enters the buffer.
next() reads up to a space or line end → "Ada". The ⏎ stays in the buffer.
nextLine() reads up to the ⏎ → returns "" (empty) and consumes the ⏎. The buffer is clean now.
The buffer is empty → nextLine() waits. The user types Giresun Merkez and presses Enter.
The whole line (spaces included) is read → "Giresun Merkez"; the ⏎ is consumed but not added to the result.
Both values are printed.
Scanner in = new Scanner(System.in);
String word = in.next();
in.nextLine();
String line = in.nextLine();
System.out.println(word + " | " + line);Without line 3, the nextLine() on line 4 would read the leftover ⏎ and return an empty line at once.
Performance
Concatenation and StringBuilder
+reads well for joining a few strings.- In a loop,
s = s + xcreates a new String on every pass and copies the old one. StringBuilderis a mutable buffer:appendadds to the same object.toString()builds the final String from the buffer's current contents.
Performance · Step through the code
Code Trace: Joining with StringBuilder
An empty, mutable buffer is created.
1 <= 3 → true
append(1) and append(' ') add to the same object (no new String) → "1 ".
i++ → 2 <= 3 → true
append(2) and append(' ') add to the same object (no new String) → "1 2 ".
i++ → 3 <= 3 → true
append(3) and append(' ') add to the same object (no new String) → "1 2 3 ".
i++ → 4 <= 3 → false: the loop ends.
toString() builds a single String from the buffer.
A | is added so the trailing space shows.
StringBuilder text = new StringBuilder(); for (int i = 1; i <= 3; i++) { text.append(i).append(' '); } String result = text.toString(); System.out.println(result + "|");
Applications · Step through the code
Reversing a String
We read the string from end to start and append to a new string.
Start with the empty string.
i = 3: append s.charAt(3) = 'a' → "a" (each += makes a new String).
i = 2: append s.charAt(2) = 'v' → "av" (each += makes a new String).
i = 1: append s.charAt(1) = 'a' → "ava" (each += makes a new String).
i = 0: append s.charAt(0) = 'J' → "avaJ" (each += makes a new String).
i = −1 → the loop ends; the result is printed.
Shortcut: StringBuilder's built-in reverse() gives the same result.
Both methods produce the same output; s never changed.
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);
Applications · Step through the code
Palindromes: Ignoring Case and Spaces
The sentence has uppercase letters and spaces; compared directly, 'E' ≠ 'e'.
toLowerCase(tr) (Turkish rules) and replace(" ", "") → "eyedipadanadapideye" (19 characters).
Two end pointers: left = 0, right = 18. Assume isPal = true until proven otherwise.
'e' and 'e' → equal; move inward.
'y' and 'y' → equal; move inward.
'e' and 'e' → equal; move inward.
'd' and 'd' → equal; move inward.
'i' and 'i' → equal; move inward.
'p' and 'p' → equal; move inward.
'a' and 'a' → equal; move inward.
'd' and 'd' → equal; move inward.
'a' and 'a' → equal; move inward.
left = 9, right = 9: the pointers met and every pair matched → true.
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);Applications · Step through the code
Counting Vowels
First the text is lowercased with Turkish rules (tr); the vowels string holds the Turkish vowels.
'm': indexOf → -1 → not a vowel.
'e': indexOf → 1 ≥ 0 → vowel, count = 1.
'r': indexOf → -1 → not a vowel.
'h': indexOf → -1 → not a vowel.
'a': indexOf → 0 ≥ 0 → vowel, count = 2.
'b': indexOf → -1 → not a vowel.
'a': indexOf → 0 ≥ 0 → vowel, count = 3.
'␣': indexOf → -1 → not a vowel.
'd': indexOf → -1 → not a vowel.
'ü': indexOf → 7 ≥ 0 → vowel, count = 4.
'n': indexOf → -1 → not a vowel.
'y': indexOf → -1 → not a vowel.
'a': indexOf → 0 ≥ 0 → vowel, count = 5.
13 characters scanned: 5 vowels.
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);Applications · Step through the code
Counting Words (space-to-letter transitions)
A word is an unbroken run of non-space characters. We count the transitions from space to letter.
'A' is a letter and we were outside a word → new word: word = 1.
'l' continues the same word.
'i' continues the same word.
Space → we left the word.
Another space (double space) → not counted.
'a' is a letter and we were outside a word → new word: word = 2.
't' continues the same word.
'a' continues the same word.
Space → we left the word.
'b' is a letter and we were outside a word → new word: word = 3.
'a' continues the same word.
'k' continues the same word.
The result is 3. Shortcut: text.trim().split("\\s+").length (only for nonblank text; blank text gives 1, not 0, so check isBlank() first).
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);
Applications · Step through the code
Character Frequency (int[26])
A 26-cell counter: 'a' → 0, 'b' → 1, … A letter's index is c - 'a' (chars are numbers). Characters outside a–z are skipped with continue.
'k' - 'a' = 107 − 97 = 10 → freq[10] = 1.
'a' - 'a' = 97 − 97 = 0 → freq[0] = 1.
'v' - 'a' = 118 − 97 = 21 → freq[21] = 1.
'a' - 'a' = 97 − 97 = 0 → freq[0] = 2.
'k' - 'a' = 107 − 97 = 10 → freq[10] = 2.
k = 0: freq > 0 → (char) ('a' + 0) = 'a' is printed.
k = 10: freq > 0 → (char) ('a' + 10) = 'k' is printed.
k = 21: freq > 0 → (char) ('a' + 21) = 'v' is printed. The table covers only a–z; ç, ğ, ı, ö, ş, ü need a separate scheme.
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]);
Applications · Step through the code
Caesar Cipher: Encrypting and Decrypting
Each letter shifts 3 places forward in the alphabet. Only lowercase English letters (a–z) are encrypted; other characters are appended unchanged. The result builds up in a StringBuilder.
'y': (24 + 3) % 26 = 1 → 'b' (past 26, so % 26 wraps around).
'a': (0 + 3) % 26 = 3 → 'd'.
'z': (25 + 3) % 26 = 2 → 'c' (past 26, so % 26 wraps around).
'i': (8 + 3) % 26 = 11 → 'l'.
'l': (11 + 3) % 26 = 14 → 'o'.
'i': (8 + 3) % 26 = 11 → 'l'.
'm': (12 + 3) % 26 = 15 → 'p'.
The ciphertext is bdclolp. Decrypting: the same loop with 26 - shift instead of shift → "yazilim".
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);
Formatting
Formatting with printf
String name = "Java"; int qty = 3; double price = 17.5; System.out.printf("%-8s %3d %7.2f%n", name, qty, price);
%-8s ← name: "Java" is left-aligned in 8 cells; the other 4 are spaces.
%3d ← qty: the integer 3 is right-aligned in 3 cells.
%7.2f ← price: "17.50" (5 characters, 2 decimals) is right-aligned in 7 cells.
%n adds a line end. Format specifiers match the arguments in order; a type mismatch is an error.
%s text, %d integer, %f floating point. On a computer with a Turkish locale, %.2f may print a comma as the decimal separator (17,50).
Basics
Unicode and Text
- A String is made of UTF-16 code units (char); Turkish letters fit in a single char.
- Some visible characters (emoji, some symbols) take two chars or several Unicode code points.
- So
length()is not always the number of characters the user sees.
Summary
Chapter Summary
A String object is immutable; toUpperCase, + and substring return new objects.
0 … length() − 1; substring(a, b): a included, b excluded, length b − a.
equals for contents, compareTo for order; == compares only references.
next reads a word, nextLine a line; StringBuilder for heavy concatenation, printf for formatting.
Summary
Review Questions
- Why is String called immutable?
- How does substring use its start and end bounds?
- What is the difference between
==andequals? - How do next and nextLine differ?
- Why might StringBuilder be preferred inside a loop?
Answers
- Once created, its characters cannot change; every “change” produces a new object.
- Start included, end excluded; the result length is end − start.
==checks whether two variables refer to the same object,equalschecks the characters.- next stops at a space or line end and leaves the ⏎ in the buffer; nextLine reads the rest of the line and consumes the ⏎.
- It appends to a single buffer instead of creating and copying a new String on every pass.
Summary
Exercises
- Count the uppercase letters, lowercase letters, digits and spaces in a sentence separately.
- Check whether two words are anagrams (e.g. "elma" – "alem") using character frequencies.
- Print a full name entered by the user as "Surname, Name" with the surname in uppercase.
- Find the longest word in a sentence (with
split). - Extend the Caesar cipher to support uppercase letters (A–Z); leave other characters as they are.
- Write code with StringBuilder that removes all spaces from a string without using
replace.
Summary
References
- Deitel and Deitel, Java: How to Program, Early Objects, 11th ed., Pearson, 2018.
- Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, The Java Tutorials: Strings, The StringBuilder Class.
- Oracle, Java SE 21 API: String, StringBuilder.
- Sedgewick and Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 3.1 Using Data Types.
- Unicode Consortium, The Unicode Standard.