Chapter 3.4: Strings
Introduction
Learning Outcomes
String objects: create them from literals and with new; explain the order of + concatenation.
charAt, length, indexOf, substring: access parts of a string and loop over its characters.
Show in memory that methods return new objects; use StringBuilder in loops.
next(), nextLine(), nextInt(): explain how they differ and avoid the leftover-newline trap.
== vs. equals(): explain the difference using the string pool; use compareTo and related methods.
printf and String.format: set width, alignment and precision.
String Basics
What Is a String?
- A string is an object that holds a sequence of characters; its type is the class
java.lang.String. Stringis a class, not a primitive type; its name is capitalized.importis not needed.- Text in double quotes, like
"Tarkan", is a string literal; the object is created withoutnew. - Characters are stored as Unicode, so Turkish letters such as
ç ğ ı İ ö ş üwork fine. - A single character is a
charin single quotes ('T'); text is aStringin double quotes ("T").
String name = "Tarkan";
String fullName = "Mustafa Sandal";
String point = "(" + 3 + ", " + 5 + ")";
System.out.println(name);
System.out.println(fullName);
System.out.println(point);Tarkan Mustafa Sandal (3, 5)
A string is like a row of character boxes.
String Basics
Creating and Concatenating Strings (+)
String s0 = "Giresun"; // literal char[] letters = {'J', 'a', 'v', 'a'}; String s1 = new String(letters); // char[] String s2 = String.valueOf(42); // from int String s3 = "Giresun".concat(" Uni."); System.out.println(s1 + " " + s2 + " " + s3); System.out.println("Sum: " + 3 + 5); System.out.println("Sum: " + (3 + 5)); System.out.println(3 + 5 + " apples"); System.out.println('a' + 'b' + "c"); System.out.println("" + 'a' + 'b');
Java 42 Giresun Uni. Sum: 35 Sum: 8 8 apples 195c ab
+: if either operand is aString, the other is converted to a string and the two are concatenated.+is evaluated left to right:"Sum: " + 3first becomes"Sum: 3", then5is appended →Sum: 35.- Parentheses give the sum:
"Sum: " + (3 + 5). 3 + 5 + " apples": the numbers are added first (8), then the string is appended.'a' + 'b'adds twocharvalues as numbers (97 + 98 = 195). Putting""first forces string concatenation.- Every concatenation creates a new
Stringobject.
String Basics · Step-by-step code trace
+ Left to Right: Addition or Concatenation?
Two int variables. On each line, + is evaluated left to right; the type is checked at every step.
Left side is a String: 4 is converted and appended → "Total: 4".
Still a String; 2 is appended as text too → "Total: 42", not a sum!
Parentheses first: 4 + 2 adds two ints: the numeric sum is 6.
Then concatenated with the string → "Total: 6".
Both left operands are int: added first → 6.
6 + " pens": now a String → "6 pens".
'x' + 'y': two chars are added as numbers: 120 + 121 = 241.
241 + "z" → "241z".
Empty string first: "" + 'x' becomes a String → "x".
"x" + 'y' → "xy": the char is appended as text.
The first line is printed.
The second line is printed. Rule: once one side is a String, + concatenates; until then, numbers are added.
int a = 4, b = 2;
String s1 = "Total: " + a + b;
String s2 = "Total: " + (a + b);
String s3 = a + b + " pens";
String s4 = 'x' + 'y' + "z";
String s5 = "" + 'x' + 'y';
System.out.println(s1 + " | " + s2);
System.out.println(s3 + " | " + s4 + " | " + s5);String Basics
Indexing
- The first character has index 0; the last has index
length() - 1. charAt(i): character at indexi(achar).length()is a method and needs parentheses (an array'slengthis a field).- An index past the end or below zero throws a runtime
StringIndexOutOfBoundsException. charis a number (its Unicode code):c + 1is a number,(char) (c + 1)is the next letter.
String name = "Tarkan"; System.out.println(name.length()); System.out.println(name.charAt(0)); System.out.println(name.charAt(name.length() - 1)); char c = name.charAt(2); System.out.println(c + 1); System.out.println((char) (c + 1));
6 T n 115 s
String s = "Java"; System.out.println(s.charAt(4));
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
Index 4 out of bounds for length 4String Basics · Step-by-step code trace
Looping over Characters: Step by Step
The prompt is printed; print does not start a new line.
The user types Giresun and presses Enter; nextLine() reads the whole line.
i = 0: charAt(0) = 'G'; the line is printed, then i += 2.
i = 2: charAt(2) = 'r'; the line is printed, then i += 2.
i = 4: charAt(4) = 's'; the line is printed, then i += 2.
i = 6: charAt(6) = 'n'; the line is printed, then i += 2.
i = 8: 8 < 7 is false: the loop ends. The last index is 6; 7 is never used.
The Scanner is closed and the program ends.
Scanner scanner = new Scanner(System.in); System.out.print("Enter a word: "); String word = scanner.nextLine(); for (int i = 0; i < word.length(); i += 2) { char letter = word.charAt(i); System.out.println("Letter " + (i + 1) + ": " + letter); } scanner.close();
String Methods
Basic String Methods
| Method | What it does | For s = "Java Programming" |
|---|---|---|
length() | Number of characters. | 16 |
charAt(i) | Character at index i (a char). | s.charAt(0) → 'J' |
indexOf(str) | Index of the first match; −1 if absent. | s.indexOf("Programming") → 5s.indexOf("C++") → -1 |
indexOf(str, from) | Searches from index from. | s.indexOf("a", 4) → 10 |
lastIndexOf(str) | Index of the last match. | s.lastIndexOf('g') → 15 |
substring(i1, i2) | From i1 to i2 (exclusive). | s.substring(5, 12) → "Program" |
substring(i1) | i1 to the end. | s.substring(5) → "Programming" |
toLowerCase() | A new lowercase string. | "java programming" |
toUpperCase() | A new uppercase string. | "JAVA PROGRAMMING" |
No method changes s; the result always comes back as a new value.
String Methods · Step-by-step code trace
indexOf and substring: Step by Step
A 16-character string; the space is a character too (index 4).
indexOf("Programming") returns the index where the match starts: 5.
length() = 16; indices 0 … 15.
substring(5, 12): 5, 6, …, 11 → "Program" (12 − 5 = 7 characters).
substring(5) → "Programming".
toLowerCase() returns a new string; str is still "Java Programming".
toUpperCase() also returns a new string. The original never changed.
String str = "Java Programming"; int index = str.indexOf("Programming"); int len = str.length(); String sub = str.substring(5, 12); String rest = str.substring(5); String lower = str.toLowerCase(); String upper = str.toUpperCase();
String Methods
Other Useful Methods
String s = " Hello World ";
System.out.println("[" + s.trim() + "]");
System.out.println("[" + s.replace('o', '0') + "]");
String[] fruits = "apple,pear,plum".split(",");
System.out.println(fruits.length);
System.out.println(fruits[1]);
System.out.println(String.join(" - ", fruits));
System.out.println("ab".repeat(3)); // Java 11+
System.out.println("".isEmpty());
System.out.println(" ".isBlank()); // Java 11+
char[] arr = "Java".toCharArray();
System.out.println(arr.length + " " + arr[0]);
System.out.println("Giresun".replace("sun", "SUN"));
System.out.println(String.valueOf(3.5) + 1);
System.out.println(Integer.parseInt("42") + 1);[Hello World] [ Hell0 W0rld ] 3 pear apple - pear - plum ababab true true 4 J GireSUN 3.51 43
trim(): removes leading and trailing spaces.replace: replaces every match.split(sep): returns the pieces as aString[]array;String.joindoes the reverse.String.valueOf(x): number → string;Integer.parseInt(s),Double.parseDouble(s): string → number.
Immutability
Immutable Objects
Stringobjects are immutable: they cannot change once created.toUpperCase,replace,substring,+do not change the original; they return a new object.- To keep the result you must assign it:
s = s.toUpperCase(); - Benefits: safe, consistent code (code sharing a string cannot break it), memory savings in the string pool, and safe sharing between threads.
String s = "Giresun Üniversitesi"; s.toUpperCase(); // result is lost System.out.println(s); s = s.toUpperCase(); // stored in s System.out.println(s);
Giresun Üniversitesi GİRESUN ÜNİVERSİTESİ
On a Turkish-locale (tr-TR) machine the output is GİRESUN ÜNİVERSİTESİ; under an English locale it is GIRESUN ÜNIVERSITESI.
Immutability · Step-by-step code trace
Immutability in Memory, Step by Step
The literal is an object in the pool; s points to it.
toUpperCase() creates a new object. But the result is not assigned to any variable!
s still points to the old object, so the original text is printed. The orphaned object is left to the garbage collector.
Again a new object is created, and this time its reference is assigned to s. The old object did not change; only the arrow moved.
s now points to the uppercase object.
String s = "Giresun Üniversitesi"; s.toUpperCase(); System.out.println(s); s = s.toUpperCase(); System.out.println(s);
Immutability
Turkish Letters and the Locale
import java.util.Locale;
String s = "Giresun Üniversitesi";
System.out.println(s.toUpperCase());
System.out.println(s.toUpperCase(Locale.ROOT));
System.out.println("TITLE".toLowerCase());
System.out.println("TITLE".toLowerCase().equals("title"));
System.out.println("TITLE".toLowerCase(Locale.ROOT));GİRESUN ÜNİVERSİTESİ GIRESUN ÜNIVERSITESI tıtle false title
| Conversion | Turkish (tr) | ROOT / English |
|---|---|---|
i → upper | İ | I |
I → lower | ı | i |
ı → upper | I | I |
- Without an argument,
toUpperCase()/toLowerCase()use the machine's default locale: the same program can give different results on another machine. - Under a Turkish locale,
"TITLE".toLowerCase()→"tıtle": the comparison isfalse! - For commands, file names and similar text, pass
Locale.ROOT; for Turkish text,Locale.forLanguageTag("tr-TR").
Immutability
Concatenation in Loops and StringBuilder
String result = ""; for (int i = 1; i <= 5; i++) { result += i + " "; // new String each time } System.out.println(result); StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 5; i++) { sb.append(i).append(' '); // same object grows } String text = sb.toString(); System.out.println(text); StringBuilder rev = new StringBuilder("Giresun"); rev.reverse(); System.out.println(rev); StringBuilder k = new StringBuilder("Java"); k.insert(0, ">> ").append('!'); k.setCharAt(3, 'j'); System.out.println(k + " " + k.length());
1 2 3 4 5 1 2 3 4 5 nuseriG >> java! 8
result += ...copies the old text on every iteration into a new object; n iterations copy about n²/2 characters.StringBuilderis a mutable character buffer:append,insert,reverse,setCharAt,deleteCharAtall work on the same object.- When done,
toString()turns it into aString. - For a few pieces,
+is fine and readable; for many concatenations inside a loop, preferStringBuilder.
Immutability · Step-by-step code trace
StringBuilder: One Buffer, Changed in Place
One mutable buffer: 4 characters used, capacity 16 + 4 = 20.
append(' '): a space is appended; same object, no new object.
The second call in the chain, append(8): the number is appended as a character. append returns the object itself, so calls can be chained.
insert(0, ">> "): the other characters shift right to make room for 3 cells at the front.
setCharAt(3, 'j'): index 3 changes in place, which a String cannot do.
deleteCharAt(8): the trailing '8' is deleted; length 8.
16 more characters: 24 > 20, no room. The buffer grows: new capacity (20 + 1) × 2 = 42, old contents copied.
toString(): creates a new String from the buffer's current contents.
Length 24 and capacity 42 are printed.
StringBuilder sb = new StringBuilder("Java");
sb.append(' ').append(8);
sb.insert(0, ">> ");
sb.setCharAt(3, 'j');
sb.deleteCharAt(sb.length() - 1);
sb.append("programming book");
String s = sb.toString();
System.out.println(s + " " + sb.length() + " " + sb.capacity());User Input
User Input: Scanner
java.util.Scannerreads input from the keyboard (System.in):import java.util.Scanner;next(): skips whitespace and reads the next word (up to a space).nextLine(): reads everything up to the end of the line; it consumes the newline but drops it from the result.nextInt(),nextDouble(): reads a number but leaves the newline after it in the buffer. If the input is not a number,InputMismatchExceptionis thrown.- When done, call
keyboard.close().
Scanner keyboard = new Scanner(System.in); System.out.println("enter some text"); String input = keyboard.next(); System.out.println(input); // algorithms input = keyboard.next(); System.out.println(input); // in input = keyboard.nextLine(); System.out.println(input); // computational terms
algorithms in computational terms
enter some text algorithms in computational terms
nextLine()'s result starts with a space: the space after “in” is part of the line too.
User Input · Step-by-step code trace
next() and nextLine(): Step by Step
The prompt is printed; the program waits for the user to enter a line.
The user types the line and presses Enter (the buffer holds ⏎ too). next() reads up to the first space: "algorithms".
The word is printed. The cursor waits before the space.
next() first skips the space, then reads "in".
Printed. The cursor is again before a space.
nextLine() does not skip the space: it reads to the end of the line and consumes ⏎: " computational terms".
Printed with the leading space. The buffer is now empty.
Scanner keyboard = new Scanner(System.in);
System.out.println("enter some text");
String input = keyboard.next();
System.out.println(input);
input = keyboard.next();
System.out.println(input);
input = keyboard.nextLine();
System.out.println(input);User Input
The nextLine() after nextInt() Trap
Wrong: the name is skipped without being asked.
Scanner keyboard = new Scanner(System.in); System.out.print("Age: "); int age = keyboard.nextInt(); System.out.print("Name: "); String name = keyboard.nextLine(); System.out.println("[" + name + "] " + age);
Age: 19 Name: [] 19
Right: consume the leftover newline.
int age = keyboard.nextInt(); keyboard.nextLine(); // drop ⏎ System.out.print("Name: "); String name = keyboard.nextLine();
Age: 19 Name: Ayşe [Ayşe] 19
nextInt() takes only 19. The nextLine() right after it reads the empty text up to ⏎. Alternative: read everything with nextLine() and convert with Integer.parseInt.
Comparison
Comparing with ==
==compares the references (memory addresses) of objects, not their contents.- If two variables point to the same object, it returns
true; for different objects it returnsfalse, even if the contents match. str1 == str2beingtrueis no accident but a result of the string pool.
== cannot compare string contents; compare contents with equals().String str1 = "Giresun"; String str2 = "Giresun"; String str3 = new String("Giresun"); System.out.println(str1 == str2); // true System.out.println(str1 == "Giresun"); // true System.out.println(str1 == str3); // false System.out.println(str3 == "Giresun"); // false
true true false false
Comparison
The String Pool
- Constants in source code such as
"giresun"are string literals. - Literals are stored in a special region of the heap, the string pool: literals with the same content share one object. This saves memory and time (it is safe because strings are immutable).
new String(...)bypasses the pool: eachnewcreates a new object.- So
==givestruefor equal literals butfalsefor equalnewobjects. - A string built with
+at run time is a new object too; a compile-time constant like"Gire" + "sun"goes to the pool.s.intern()returns the pooled copy.
Two literals share one object; new creates a separate one.
Comparison · Step-by-step code trace
The String Pool: Step by Step
The pool holds an object for the literal "Giresun"; str1 points to it.
The same literal is reused: no new object is created, str2 also points to it.
new always creates a new object outside the pool (same content).
str1 and str2 are the same object (#1) → true.
"Giresun" is also the pooled #1 → true.
#1 and #2 are different objects (same content) → false.
#2 differs from the pooled #1 → false.
String str1 = "Giresun";
String str2 = "Giresun";
String str3 = new String("Giresun");
System.out.println(str1 == str2);
System.out.println(str1 == "Giresun");
System.out.println(str1 == str3);
System.out.println(str3 == "Giresun");Comparison
Comparing Contents with equals()
String str1 = "Giresun"; String str2 = "Giresun"; String str3 = new String("Giresun"); System.out.println(str1.equals(str2)); System.out.println(str1.equals("Giresun")); System.out.println(str1.equals(str3)); System.out.println(str3.equals("Giresun")); System.out.println(str3.intern() == str1); String a = "Gire"; String b = a + "sun"; // new object System.out.println(b == str1); System.out.println(b.equals(str1));
true true true true true false true
equals()compares contents character by character: the first four aretrue.- How the object was made (literal,
new, concatenation,Scanner) does not matter. - User input is created at run time:
input == "yes"is almost alwaysfalse.
String answer = null; System.out.println("yes".equals(answer)); // false System.out.println(answer.equals("yes")); // error!
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.equals(Object)" because "answer" is nullPutting the literal first ("yes".equals(answer)) is safe against null.
Comparison
Comparison Methods
| Method | Returns | Description |
|---|---|---|
equals(str) | boolean | Exactly the same contents? |
equalsIgnoreCase(str) | boolean | The same, ignoring case? |
startsWith(str) | boolean | Does the string start with the given string? |
endsWith(str) | boolean | Does the string end with the given string? |
contains(str) | boolean | Does the given string occur inside it? |
isEmpty() / isBlank() | boolean | Length 0? / Only whitespace? (isBlank: Java 11+) |
compareTo(str) | int | Lexicographic order: negative (before), 0 (equal), positive (after). |
compareToIgnoreCase(str) | int | Case-insensitive compareTo. |
All are case-sensitive (except those with IgnoreCase in the name), and with a null argument, equals/equalsIgnoreCase simply return false.
Comparison
Comparison Methods: Example
String s = "Giresun Üni.";
System.out.println(s.startsWith("Gir")); // true
System.out.println(s.startsWith("Gır")); // false
System.out.println(s.endsWith("Üni.")); // true
System.out.println(s.endsWith("Üni")); // false
System.out.println(s.equalsIgnoreCase("Giresun Üni.")); // true
System.out.println(s.equalsIgnoreCase("Gıresun üni.")); // true
System.out.println(s.equalsIgnoreCase("GIresun Uni.")); // false
System.out.println(s.contains("Üni")); // true- The comments show the program's actual output.
"Gır":ıandiare different characters →false."Üni": the string ends with a period →false.equalsIgnoreCasecompares after converting characters to uppercase:ıandiboth becomeI→"Gıresun üni."counts as equal."GIresun Uni.":UandÜare different letters →false.
Comparison
compareTo: Lexicographic Order
System.out.println("egg".compareTo("apple"));
System.out.println("apple".compareTo("egg"));
System.out.println("egg".compareTo("egg"));
System.out.println("Egg".compareTo("egg"));
System.out.println("Egg".compareToIgnoreCase("egg"));
System.out.println("do".compareTo("door"));
System.out.println("çay".compareTo("dut"));4 -4 0 -32 0 -2 131
a.compareTo(b):acomes first → negative; equal → 0; after → positive.- The Unicode codes of the first differing characters are subtracted:
'e' − 'a'= 101 − 97 = 4. 'E' − 'e'= 69 − 101 = −32: uppercase letters come before lowercase.- If one is a prefix of the other, the length difference is returned:
"do"vs"door"→ 2 − 4 = −2. 'ç'(231) >'d'(100):compareTodoes not know Turkish alphabetical order, so “çay” comes after “dut”. For correct Turkish sorting usejava.text.Collator.- Used for sorting (e.g.
Arrays.sort) and in tests likeif (a.compareTo(b) < 0).<,>do not work on strings.
Comparison · Step-by-step code trace
compareTo: Up to the First Difference
compareTo compares two strings character by character from the start.
k = 0: 'c' (99) and 'c' (99) are equal; continue.
k = 1: 'a' and 'a' are equal.
k = 2: 's' (115) and 'v' (118) differ: the comparison stops here.
The result is the code difference: 115 − 118 = −3. Negative: "case" comes first.
"car" and "cargo": the first 3 characters match and the shorter one runs out.
One is a prefix of the other: the length difference is returned, 3 − 5 = −2.
The first characters differ: 'Z' (90) − 'a' (97) = −7. Uppercase comes before lowercase: even Z precedes a!
-3 -2 -7 is printed.
String a = "case", b = "cave"; int r1 = a.compareTo(b); int r2 = "car".compareTo("cargo"); int r3 = "Zeki".compareTo("ali"); System.out.println(r1 + " " + r2 + " " + r3);
Formatted Output
The printf Method
- Usage:
System.out.printf("format string", args); - The format string holds format specifiers; the arguments fill them in order.
printfadds no newline: append\nor the portable%n.- Width:
%Wd→ W characters, right-aligned;%-Wd→ W characters, left-aligned. - Precision:
%.2f→ 2 decimal places (rounded);%8.2f→ 8 characters in total. - A wider value is not cut; the field grows.
| Specifier | Type | Example → output |
|---|---|---|
%d | Integer | 42 → 42 |
%f | Decimal (float, double) | %.1f: 3.14159 → 3,1 |
%s | String | %5s: "ab" → ␣␣␣ab |
%c | Character | 'Z' → Z |
%b | Boolean | true → true |
%n | Newline | — |
The decimal separator depends on the locale: in tr-TR it is 3,1, with Locale.US it is 3.1.
Formatted Output
printf: Example
int i = 3; float f = -17; String s = "java"; System.out.printf("x: %d y: %f s: %s\n", i, f, s); System.out.printf("x: %4d y: %5.2f s: %6s\n", i, f, s); System.out.printf("x: %-4d y: %-7.2f s: %-6s\n", i, f, s); System.out.printf("x: %-4d y: %-6.3f s: %-6s\n", i, f, s);
x: 3 y: -17,000000 s: java x: 3 y: -17,00 s: java x: 3 y: -17,00 s: java·· x: 3 y: -17,000 s: java··
%fprints 6 decimal places by default:-17,000000. Under a Turkish locale the decimal separator is a comma.%5.2f:-17,00is already 6 characters, so width 5 has no effect.%-6.3f:-17,000is 7 characters; the field grows.%6s→␣␣java(right-aligned);%-6s→java␣␣(left-aligned, padded on the right).
Formatted Output · Step-by-step code trace
Width and Precision, Character by Character
Without a width, each value takes exactly its own length; %f prints 6 decimal places.
%4d and %6s right-align the value, padding the left with spaces. -17,00 is 6 characters: it does not fit width 5, so the field grows.
The minus sign left-aligns: spaces go to the right of the value, so columns line up neatly.
%-6.3f: 3 decimals → -17,000 7 characters; wider than 6, so no padding.
int i = 3; float f = -17; String s = "java"; System.out.printf("x: %d y: %f s: %s\n", i, f, s); System.out.printf("x: %4d y: %5.2f s: %6s\n", i, f, s); System.out.printf("x: %-4d y: %-7.2f s: %-6s\n", i, f, s); System.out.printf("x: %-4d y: %-6.3f s: %-6s\n", i, f, s);
Formatted Output
More Formats and String.format
System.out.printf("|%5s|%-5s|%05d|%.1f|%n", "ab", "ab", 42, 3.14159);
System.out.printf("%c %b %e %x %%%n", 'Z', true, 1234.5, 255);
String msg = String.format("%s: %d points", "Ayşe", 85);
System.out.println(msg);
System.out.printf("%,d%n", 1234567);
System.out.printf(Locale.US, "%.2f%n", 2.5); // import java.util.Locale;
System.out.println("%s = %d".formatted("x", 7)); // Java 15+| ab|ab |00042|3,1| Z true 1,234500e+03 ff % Ayşe: 85 points 1.234.567 2.50 x = 7
%05dpads with leading zeros,%,dadds a thousands separator (tr-TR: period),%escientific,%xhexadecimal,%%is a percent sign.String.format(...)uses the same rules but, instead of printing, returns the formatted string.- The first argument can be a
Locale:Locale.USgives a period as the decimal separator. - A type mismatch is a runtime error:
printf("%d", 3.5)→IllegalFormatConversionException.
Applications · Step-by-step code trace
Palindrome Check: Step by Step
The text entered by the user: "Kayak".
toLowerCase() converts it to lowercase (the new object is assigned to text).
An empty string is prepared for the result.
i = 4: charAt(4) = 'k' is appended → "k".
i = 3: charAt(3) = 'a' is appended → "ka".
i = 2: charAt(2) = 'y' is appended → "kay".
i = 1: charAt(1) = 'a' is appended → "kaya".
i = 0: charAt(0) = 'k' is appended → "kayak".
i = -1: -1 >= 0 is false; the loop ends.
The reversed text is printed.
Same contents: equals → true, so “kayak” is a palindrome.
String text = "Kayak"; text = text.toLowerCase(); String rev = ""; for (int i = text.length() - 1; i >= 0; i--) { rev += text.charAt(i); } System.out.println(rev); System.out.println(text.equals(rev));
A palindrome reads the same backward (kayak, level, noon). For sentences, first remove non-letters: text.replaceAll("[^\\p{L}]", "") (only letters remain). A shortcut for reversing: new StringBuilder(text).reverse().toString(); “A man, a plan, a canal: Panama” is a palindrome once cleaned.
Applications
Application: Word Frequency
String text = "One two one six TWO one";
String[] words = text.toLowerCase().split(" ");
boolean[] counted = new boolean[words.length];
for (int i = 0; i < words.length; i++) {
if (counted[i]) {
continue; // already counted
}
int freq = 1;
for (int j = i + 1; j < words.length; j++) {
if (words[i].equals(words[j])) {
freq++;
counted[j] = true;
}
}
System.out.println(words[i] + ": " + freq);
}one: 3 two: 2 six: 1
toLowerCase()makes “One/one” and “TWO/two” the same word.split(" ")splits the text into words.- Words are compared with
equals:splitreturns separate objects, so==gives wrong results. - The
countedarray stops a word being reported twice.
Applications · Step-by-step code trace
Word Frequency: Counting with Flags
Lowercased and split on spaces: an array of 5 words. "Pear" and "PEAR" are now the same.
counted: one flag per word, all false.
i = 0 (apple): the inner loop scans the words to the right with equals; j = 2 matches → freq 2, counted[2] = true.
apple: 2 is printed.
i = 1 (pear): j = 4 matches → freq 2, counted[4] = true.
pear: 2 is printed.
i = 2: flag is true, this apple was already counted → continue.
i = 3 (plum): no match, freq 1.
i = 4: already counted, skipped. The loop ends.
String text = "apple Pear apple plum PEAR";
String[] k = text.toLowerCase().split(" ");
boolean[] counted = new boolean[k.length];
for (int i = 0; i < k.length; i++) {
if (counted[i]) continue;
int freq = 1;
for (int j = i + 1; j < k.length; j++) {
if (k[i].equals(k[j])) {
freq++;
counted[j] = true;
}
}
System.out.println(k[i] + ": " + freq);
}Summary
Summary
| Concept | Key idea |
|---|---|
String | An immutable object holding a character sequence; created from a literal ("...") or with new. |
| Index | 0 … length() - 1; charAt(i) returns a char. |
+ | Left to right: concatenation once one side is a string; use parentheses to add numbers. |
| Methods | indexOf (−1 = not found), substring(a, b) (b excluded), toUpperCase, replace, split, trim… all return new values. |
StringBuilder | Mutable buffer for heavy concatenation in loops. |
Scanner | next() a word, nextLine() a line; nextInt() leaves ⏎ in the buffer. |
== / equals | Same object? / Same contents? For strings, always use equals. |
| String pool | Equal literals share one object; new and runtime concatenation create new objects. |
| Comparison | equalsIgnoreCase, startsWith, endsWith, contains, compareTo (Unicode order). |
printf | %d %f %s; %Wd right-, %-Wd left-aligned; %.2f precision; separators depend on the locale. |
Summary
Common Mistakes (1): Compiler Errors
error: unclosed character literalString s = 'Hello'; Single quotes are for one character only; strings use double quotes.error: incompatible types: String cannot be converted to charchar c = "a"; → use char c = 'a'; or "a".charAt(0).error: cannot find symbol symbol: variable lengthFor strings, s.length() is a method. The reverse is an error too: for an array, d.length() → symbol: method length().error: cannot find symbol symbol: class stringThe class name is String; Java is case-sensitive.error: incompatible types: String cannot be converted to intint n = "42"; → use Integer.parseInt("42").error: unexpected type required: variables.charAt(0) = 'j'; is illegal: strings are immutable. Fix: build a new string or use StringBuilder.setCharAt.Summary
Common Mistakes (2): Logic and Runtime
if (input == "yes") // compiles but wrongUser input is a new object; the condition is false. Correct: "yes".equals(input).s.toUpperCase(); // s unchangedStrings are immutable; write s = s.toUpperCase();.StringIndexOutOfBoundsException: Index 4 out of bounds for length 4The last character is s.charAt(s.length() - 1); the loop condition is i < s.length().String name = keyboard.nextLine(); // ""The leftover ⏎ is read. Fix: add an extra keyboard.nextLine();.NullPointerException: Cannot invoke "String.equals(Object)"With the literal first, there is no error: "yes".equals(answer).s.substring(5, 12) // 7 charsThe end index is exclusive: length = end − start.Summary
Worked Problems (1)
Problem 1. What does it print?
String s = "Karadeniz";
s.toUpperCase();
String t = s.substring(2, 5);
System.out.println(t + " " + t.length());
System.out.println(s.indexOf("de"));
System.out.println(s.indexOf("x"));
System.out.println(1 + 2 + "3" + 4 + 5);Problem 2. What does it print?
String a = "code";
String b = "co" + "de";
String c = new String("code");
String d = c;
System.out.println(a == b);
System.out.println(a == c);
System.out.println(c == d);
System.out.println(a.equals(c));Show answers
- rad 3 / 4 / -1 / 3345.
toUpperCase()'s result is not assigned, sosis unchanged.substring(2, 5)→ indices 2, 3, 4 = "rad" (3 characters). "de" starts at index 4; there is no "x" → −1. The last line goes left to right: 1 + 2 = 3, then concatenation with "3" → "33", then "334", "3345". - true / false / true / true.
"co" + "de"is a compile-time constant → the same object as the pooleda.cis a separatenewobject;d = cis the same reference. The contents match, soequalsgivestrue.
Summary
Worked Problems (2)
Problem 3. Write the output character by character (tr-TR).
String name = "Ali";
double grade = 72.456;
System.out.printf("[%-5s][%3d][%7.2f]%n", name, 7, grade);Problem 4. What does it print?
public static String initials(String first, String last) { return first.charAt(0) + "." + last.charAt(0) + "."; } System.out.println(initials("Sercan", "Külcü")); String e = "student@giresun.edu.tr"; int at = e.indexOf('@'); System.out.println(e.substring(0, at)); System.out.println(e.substring(at + 1));
Show answers
[Ali ][ 7][ 72,46].%-5s: "Ali" + 2 spaces;%3d: 2 spaces + "7";%7.2f: "72,46" (rounded) with 2 leading spaces.- S.K. / student / giresun.edu.tr.
char + "."is a string, so this is concatenation (twochars would add up to a number).@is at index 7:substring(0, 7)andsubstring(8).
Summary
Exercises (1)
- Write
reverse(String s):reverse("Giresun")→"nuseriG". count(String s, char target): returns how many times the character occurs.count("Karadeniz", 'a')→ ?capitalize(String word): first letter uppercase, the rest lowercase.capitalize("jAVA")→"Java".
Show answers
static String reverse(String s) { String rev = ""; for (int i = s.length() - 1; i >= 0; i--) { rev += s.charAt(i); } return rev; }
static String capitalize(String word) { return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase(); }
static int count(String s, char target) { int n = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == target) { n++; } } return n; }
Outputs: nuseriG · 2 · Java. char values can be compared with == (primitive type); Karadeniz → 2.
Summary
Exercises (2)
"Object oriented programming with Java": how many words? Find out in one line.- Write a program that counts the vowels in a word.
"Ordu"→ ? - Ask for the age, then the full name, and print “Name: …, Age: …” with
printf, avoiding thenextInttrap.
Show answers
String word = "Ordu"; String vowels = "aeiouAEIOU"; int count = 0; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (vowels.indexOf(c) != -1) { count++; } } System.out.println("Vowels: " + count);
4) sentence.split(" ").length → 5. 5) Output: Vowels: 2 (O, u).
Scanner k = new Scanner(System.in); System.out.print("Age: "); int age = k.nextInt(); k.nextLine(); // drop the newline System.out.print("Name: "); String name = k.nextLine(); System.out.printf("Name: %s, Age: %d%n", name, age);
Age: 20 Name: Ali Veli Name: Ali Veli, Age: 20
Summary
References
- Oracle, The Java Tutorials: “Strings”, “Comparing Strings and Portions of Strings”, “The StringBuilder Class”, “Formatting Numeric Print Output”.
- Oracle, Java SE 21 API Documentation:
java.lang.String,java.lang.StringBuilder,java.util.Scanner,java.util.Formatter,java.util.Locale. - J. Gosling et al., The Java Language Specification, Java SE 21 Edition (§3.10.5 String Literals, §15.18.1 String Concatenation Operator +).
- P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson, 2017 (Chapter 14: Strings, Characters and Regular Expressions).
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., 2022 (Section 3.6: Strings).
- A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (Chapter 6: Loops and Strings).