Chapter 3.4: Strings

Object Oriented Programming with Java
The String objectIndexingBasic methodsImmutability StringBuilderInput with Scanner== and equals()String pool compareToprintf and formatting
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Creating strings

String objects: create them from literals and with new; explain the order of + concatenation.

Indexing and methods

charAt, length, indexOf, substring: access parts of a string and loop over its characters.

Immutability

Show in memory that methods return new objects; use StringBuilder in loops.

User input

next(), nextLine(), nextInt(): explain how they differ and avoid the leftover-newline trap.

Comparison

== vs. equals(): explain the difference using the string pool; use compareTo and related methods.

Formatted output

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.
  • String is a class, not a primitive type; its name is capitalized. import is not needed.
  • Text in double quotes, like "Tarkan", is a string literal; the object is created without new.
  • Characters are stored as Unicode, so Turkish letters such as ç ğ ı İ ö ş ü work fine.
  • A single character is a char in single quotes ('T'); text is a String in 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);
Output
Tarkan
Mustafa Sandal
(3, 5)
T0a1r2k3a4n5

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');
Output
Java 42 Giresun Uni.
Sum: 35
Sum: 8
8 apples
195c
ab
  • +: if either operand is a String, the other is converted to a string and the two are concatenated.
  • + is evaluated left to right: "Sum: " + 3 first becomes "Sum: 3", then 5 is 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 two char values as numbers (97 + 98 = 195). Putting "" first forces string concatenation.
  • Every concatenation creates a new String object.

String Basics · Step-by-step code trace

+ Left to Right: Addition or Concatenation?

a = 4 b = 2int int

Two int variables. On each line, + is evaluated left to right; the type is checked at every step.

"Total: "String4int+"Total: 4" (String)

Left side is a String: 4 is converted and appended → "Total: 4".

"Total: 4"String2int+"Total: 42" (String)

Still a String; 2 is appended as text too → "Total: 42", not a sum!

4int2int+6 (int)

Parentheses first: 4 + 2 adds two ints: the numeric sum is 6.

"Total: "String6int+"Total: 6" (String)

Then concatenated with the string → "Total: 6".

4int2int+6 (int)

Both left operands are int: added first → 6.

6int" pens"String+"6 pens" (String)

6 + " pens": now a String → "6 pens".

'x'char'y'char+241 (int)

'x' + 'y': two chars are added as numbers: 120 + 121 = 241.

241int"z"String+"241z" (String)

241 + "z" → "241z".

""String'x'char+"x" (String)

Empty string first: "" + 'x' becomes a String → "x".

"x"String'y'char+"xy" (String)

"x" + 'y' → "xy": the char is appended as text.

printlnconcatenated strings are printed

The first line is printed.

printlnconcatenated strings are 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 index i (a char).
  • length() is a method and needs parentheses (an array's length is a field).
  • An index past the end or below zero throws a runtime StringIndexOutOfBoundsException.
  • char is a number (its Unicode code): c + 1 is a number, (char) (c + 1) is the next letter.
T0a1r2k3a4n5charAt(0)charAt(5)length() = 6
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));
Output
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 4

String Basics · Step-by-step code trace

Looping over Characters: Step by Step

word not read yet

The prompt is printed; print does not start a new line.

G0i1r2e3s4u5n6

The user types Giresun and presses Enter; nextLine() reads the whole line.

G0i1r2e3s4u5n6i = 0

i = 0: charAt(0) = 'G'; the line is printed, then i += 2.

G0i1r2e3s4u5n6✓i = 2

i = 2: charAt(2) = 'r'; the line is printed, then i += 2.

G0i1r2e3s4u5n6✓✓i = 4

i = 4: charAt(4) = 's'; the line is printed, then i += 2.

G0i1r2e3s4u5n6✓✓✓i = 6

i = 6: charAt(6) = 'n'; the line is printed, then i += 2.

G0i1r2e3s4u5n6✓✓✓✓i = 8 → 8 < 7 false

i = 8: 8 < 7 is false: the loop ends. The last index is 6; 7 is never used.

G0i1r2e3s4u5n6✓✓✓✓i = 8 → 8 < 7 false

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

MethodWhat it doesFor 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") → 5
s.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

J0a1v2a3␣4P5r6o7g8r9a10m11m12i13n14g15

A 16-character string; the space is a character too (index 4).

J0a1v2a3␣4P5r6o7g8r9a10m11m12i13n14g155 ← first match

indexOf("Programming") returns the index where the match starts: 5.

J0a1v2a3␣4P5r6o7g8r9a10m11m12i13n14g1516 characters

length() = 16; indices 0 … 15.

J0a1v2a3␣4P5r6o7g8r9a10m11m12i13n14g155 included12 excluded

substring(5, 12): 5, 6, …, 11 → "Program" (12 − 5 = 7 characters).

J0a1v2a3␣4P5r6o7g8r9a10m11m12i13n14g155 to the end

substring(5) → "Programming".

j0a1v2a3␣4p5r6o7g8r9a10m11m12i13n14g15new object

toLowerCase() returns a new string; str is still "Java Programming".

J0A1V2A3␣4P5R6O7G8R9A10M11M12I13N14G15new object

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);
Output
[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 a String[] array; String.join does the reverse.
  • String.valueOf(x): number → string; Integer.parseInt(s), Double.parseDouble(s): string → number.

Immutability

Immutable Objects

  • String objects 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.
Analogy: a string is a stone tablet. It cannot be scraped and fixed; a new tablet is carved and replaces the old one.
s"Giresun Üniversitesi""GİRESUN ÜNİVERSİTESİ"old object unchanged
String s = "Giresun Üniversitesi";
s.toUpperCase();      // result is lost
System.out.println(s);
s = s.toUpperCase();  // stored in s
System.out.println(s);
Output
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

StackHeapmain()string pool"Giresun Üniversitesi"s

The literal is an object in the pool; s points to it.

StackHeapmain()string pool"Giresun Üniversitesi""GİRESUN ÜNİVERSİTESİ"s

toUpperCase() creates a new object. But the result is not assigned to any variable!

StackHeapmain()string pool"Giresun Üniversitesi""GİRESUN ÜNİVERSİTESİ"s

s still points to the old object, so the original text is printed. The orphaned object is left to the garbage collector.

StackHeapmain()string pool"Giresun Üniversitesi""GİRESUN ÜNİVERSİTESİ""GİRESUN ÜNİVERSİTESİ"s

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.

StackHeapmain()string pool"Giresun Üniversitesi""GİRESUN ÜNİVERSİTESİ"s

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));
Output (tr-TR)
GİRESUN ÜNİVERSİTESİ
GIRESUN ÜNIVERSITESI
tıtle
false
title
ConversionTurkish (tr)ROOT / English
i → upperİI
I → lowerıi
ı → upperII
  • 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 is false!
  • 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());
Output
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.
  • StringBuilder is a mutable character buffer: append, insert, reverse, setCharAt, deleteCharAt all work on the same object.
  • When done, toString() turns it into a String.
  • For a few pieces, + is fine and readable; for many concatenations inside a loop, prefer StringBuilder.

Immutability · Step-by-step code trace

StringBuilder: One Buffer, Changed in Place

Javalength = 4capacity = 20

One mutable buffer: 4 characters used, capacity 16 + 4 = 20.

Java·length = 5capacity = 20

append(' '): a space is appended; same object, no new object.

Java·8length = 6capacity = 20

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.

>>·Java·8length = 9capacity = 20

insert(0, ">> "): the other characters shift right to make room for 3 cells at the front.

>>·java·8length = 9capacity = 20

setCharAt(3, 'j'): index 3 changes in place, which a String cannot do.

>>·java·length = 8capacity = 20▲ deleted

deleteCharAt(8): the trailing '8' is deleted; length 8.

>>·java·programming·book…length = 24capacity = 4220 → 42: new array, contents copied

16 more characters: 24 > 20, no room. The buffer grows: new capacity (20 + 1) × 2 = 42, old contents copied.

>>·java·programming·book…length = 24capacity = 42s: new String (immutable)

toString(): creates a new String from the buffer's current contents.

>>·java·programming·book…length = 24capacity = 42s: new String (immutable)

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.Scanner reads 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, InputMismatchException is 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
Input (keyboard)
algorithms in computational terms
Output
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

Input buffer (empty)(nothing typed yet)

The prompt is printed; the program waits for the user to enter a line.

Input bufferalgorithms␣in␣computational␣terms⏎cursor

The user types the line and presses Enter (the buffer holds ⏎ too). next() reads up to the first space: "algorithms".

Input bufferalgorithms␣in␣computational␣terms⏎cursor

The word is printed. The cursor waits before the space.

Input bufferalgorithms␣in␣computational␣terms⏎cursor

next() first skips the space, then reads "in".

Input bufferalgorithms␣in␣computational␣terms⏎cursor

Printed. The cursor is again before a space.

Input bufferalgorithms␣in␣computational␣terms⏎cursor

nextLine() does not skip the space: it reads to the end of the line and consumes ⏎: " computational terms".

Input bufferalgorithms␣in␣computational␣terms⏎cursor

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);
Console (input: 19 ⏎ Ayşe ⏎)
Age: 19
Name: [] 19

Right: consume the leftover newline.

int age = keyboard.nextInt();
keyboard.nextLine();          // drop ⏎
System.out.print("Name: ");
String name = keyboard.nextLine();
Console
Age: 19
Name: Ayşe
[Ayşe] 19
Buffer after nextInt()19⏎Ayşe⏎cursor before ⏎

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 returns false, even if the contents match.
  • str1 == str2 being true is no accident but a result of the string pool.
Bottom line: == 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
Output
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: each new creates a new object.
  • So == gives true for equal literals but false for equal new objects.
  • 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.
StackHeapmain()string pool"Giresun""Giresun"str1str2str3

Two literals share one object; new creates a separate one.

Comparison · Step-by-step code trace

The String Pool: Step by Step

StackHeapmain()string pool"Giresun"str1str2?str3?

The pool holds an object for the literal "Giresun"; str1 points to it.

StackHeapmain()string pool"Giresun"str1str2str3?

The same literal is reused: no new object is created, str2 also points to it.

StackHeapmain()string pool"Giresun""Giresun"str1str2str3

new always creates a new object outside the pool (same content).

StackHeapmain()string pool"Giresun""Giresun"str1str2str3

str1 and str2 are the same object (#1) → true.

StackHeapmain()string pool"Giresun""Giresun"str1str2str3

"Giresun" is also the pooled #1 → true.

StackHeapmain()string pool"Giresun""Giresun"str1str2str3

#1 and #2 are different objects (same content) → false.

StackHeapmain()string pool"Giresun""Giresun"str1str2str3

#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));
Output
true
true
true
true
true
false
true
  • equals() compares contents character by character: the first four are true.
  • How the object was made (literal, new, concatenation, Scanner) does not matter.
  • User input is created at run time: input == "yes" is almost always false.
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 null

Putting the literal first ("yes".equals(answer)) is safe against null.

Comparison

Comparison Methods

MethodReturnsDescription
equals(str)booleanExactly the same contents?
equalsIgnoreCase(str)booleanThe same, ignoring case?
startsWith(str)booleanDoes the string start with the given string?
endsWith(str)booleanDoes the string end with the given string?
contains(str)booleanDoes the given string occur inside it?
isEmpty() / isBlank()booleanLength 0? / Only whitespace? (isBlank: Java 11+)
compareTo(str)intLexicographic order: negative (before), 0 (equal), positive (after).
compareToIgnoreCase(str)intCase-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": ı and i are different characters → false.
  • "Üni": the string ends with a period → false.
  • equalsIgnoreCase compares after converting characters to uppercase: ı and i both become I → "Gıresun üni." counts as equal.
  • "GIresun Uni.": U and Ü are different letters → false.
Giresun·Üni.startsWith("Gir")endsWith("Üni.")contains("Üni")

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"));
Output
4
-4
0
-32
0
-2
131
  • a.compareTo(b): a comes 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): compareTo does not know Turkish alphabetical order, so “çay” comes after “dut”. For correct Turkish sorting use java.text.Collator.
  • Used for sorting (e.g. Arrays.sort) and in tests like if (a.compareTo(b) < 0). <, > do not work on strings.

Comparison · Step-by-step code trace

compareTo: Up to the First Difference

case · cave · car · cargo · Zeki · ali

compareTo compares two strings character by character from the start.

"case"c109ase"cave"c109ave

k = 0: 'c' (99) and 'c' (99) are equal; continue.

"case"ca97se"cave"ca97ve

k = 1: 'a' and 'a' are equal.

"case"cas115e"cave"cav118e

k = 2: 's' (115) and 'v' (118) differ: the comparison stops here.

"case"cas115e"cave"cav118e= -3

The result is the code difference: 115 − 118 = −3. Negative: "case" comes first.

"car"car114"cargo"car114go

"car" and "cargo": the first 3 characters match and the shorter one runs out.

"car"car"cargo"cargo= -2

One is a prefix of the other: the length difference is returned, 3 − 5 = −2.

"Zeki"Z90eki"ali"a97li= -7

The first characters differ: 'Z' (90) − 'a' (97) = −7. Uppercase comes before lowercase: even Z precedes a!

-3 -2 -7

-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.
  • printf adds no newline: append \n or 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.
SpecifierTypeExample → output
%dInteger42 → 42
%fDecimal (float, double)%.1f: 3.14159 → 3,1
%sString%5s: "ab" → ␣␣␣ab
%cCharacter'Z' → Z
%bBooleantrue → true
%nNewline—

The decimal separator depends on the locale: in tr-TR it is 3,1, with Locale.US it is 3.1.

%start-left-align8width.2precisionftype

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);
Output (tr-TR; trailing spaces shown as ·)
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··
  • %f prints 6 decimal places by default: -17,000000. Under a Turkish locale the decimal separator is a comma.
  • %5.2f: -17,00 is already 6 characters, so width 5 has no effect. %-6.3f: -17,000 is 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

x:␣3␣y:␣-17,000000␣s:␣java%d (1)%f (10)%s (4)

Without a width, each value takes exactly its own length; %f prints 6 decimal places.

x:␣␣␣␣3␣y:␣-17,00␣s:␣␣␣java%4d (4)%5.2f (6)%6s (6)

%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.

x:␣3␣␣␣␣y:␣-17,00␣␣s:␣java␣␣%-4d (4)%-7.2f (7)%-6s (6)

The minus sign left-aligns: spaces go to the right of the value, so columns line up neatly.

x:␣3␣␣␣␣y:␣-17,000␣s:␣java␣␣%-4d (4)%-6.3f (7)%-6s (6)

%-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+
Output
|   ab|ab   |00042|3,1|
Z true 1,234500e+03 ff %
Ayşe: 85 points
1.234.567
2.50
x = 7
  • %05d pads with leading zeros, %,d adds a thousands separator (tr-TR: period), %e scientific, %x hexadecimal, %% 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.US gives 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

textK0a1y2a3k4rev"" (empty)

The text entered by the user: "Kayak".

textk0a1y2a3k4rev"" (empty)

toLowerCase() converts it to lowercase (the new object is assigned to text).

textk0a1y2a3k4rev"" (empty)

An empty string is prepared for the result.

textk0a1y2a3k4revk

i = 4: charAt(4) = 'k' is appended → "k".

textk0a1y2a3k4revka

i = 3: charAt(3) = 'a' is appended → "ka".

textk0a1y2a3k4revkay

i = 2: charAt(2) = 'y' is appended → "kay".

textk0a1y2a3k4revkaya

i = 1: charAt(1) = 'a' is appended → "kaya".

textk0a1y2a3k4revkayak

i = 0: charAt(0) = 'k' is appended → "kayak".

textk0a1y2a3k4revkayak

i = -1: -1 >= 0 is false; the loop ends.

textk0a1y2a3k4revkayak

The reversed text is printed.

textk0a1y2a3k4revkayak

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);
}
Output
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: split returns separate objects, so == gives wrong results.
  • The counted array stops a word being reported twice.
one0falsetwo1falseone2truesix3falsetwo4falseone5trueAfter i = 0: "one" 3 times, copies flagged

Applications · Step-by-step code trace

Word Frequency: Counting with Flags

kapple0pear1apple2plum3pear4

Lowercased and split on spaces: an array of 5 words. "Pear" and "PEAR" are now the same.

kapple0falsepear1falseapple2falseplum3falsepear4falsecounted

counted: one flag per word, all false.

kapple0falsepear1falseapple2trueplum3falsepear4falsecounted

i = 0 (apple): the inner loop scans the words to the right with equals; j = 2 matches → freq 2, counted[2] = true.

kapple0falsepear1falseapple2trueplum3falsepear4falsecounted

apple: 2 is printed.

kapple0falsepear1falseapple2trueplum3falsepear4truecounted

i = 1 (pear): j = 4 matches → freq 2, counted[4] = true.

kapple0falsepear1falseapple2trueplum3falsepear4truecounted

pear: 2 is printed.

kapple0falsepear1falseapple2trueplum3falsepear4truecounted

i = 2: flag is true, this apple was already counted → continue.

kapple0falsepear1falseapple2trueplum3falsepear4truecounted

i = 3 (plum): no match, freq 1.

kapple0falsepear1falseapple2trueplum3falsepear4truecounted

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

ConceptKey idea
StringAn immutable object holding a character sequence; created from a literal ("...") or with new.
Index0 … length() - 1; charAt(i) returns a char.
+Left to right: concatenation once one side is a string; use parentheses to add numbers.
MethodsindexOf (−1 = not found), substring(a, b) (b excluded), toUpperCase, replace, split, trim… all return new values.
StringBuilderMutable buffer for heavy concatenation in loops.
Scannernext() a word, nextLine() a line; nextInt() leaves ⏎ in the buffer.
== / equalsSame object? / Same contents? For strings, always use equals.
String poolEqual literals share one object; new and runtime concatenation create new objects.
ComparisonequalsIgnoreCase, 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

A string in single quoteserror: unclosed character literalString s = 'Hello'; Single quotes are for one character only; strings use double quotes.
Assigning a string to a charerror: incompatible types: String cannot be converted to charchar c = "a"; → use char c = 'a'; or "a".charAt(0).
length without parentheseserror: 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().
string in lowercaseerror: cannot find symbol symbol: class stringThe class name is String; Java is case-sensitive.
Assigning a string to a numbererror: incompatible types: String cannot be converted to intint n = "42"; → use Integer.parseInt("42").
Changing a character in placeerror: 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

Comparing contents with ==if (input == "yes") // compiles but wrongUser input is a new object; the condition is false. Correct: "yes".equals(input).
Forgetting to assign the results.toUpperCase(); // s unchangedStrings are immutable; write s = s.toUpperCase();.
Taking length() as the last indexStringIndexOutOfBoundsException: Index 4 out of bounds for length 4The last character is s.charAt(s.length() - 1); the loop condition is i < s.length().
nextLine after nextIntString name = keyboard.nextLine(); // ""The leftover ⏎ is read. Fix: add an extra keyboard.nextLine();.
Calling a method on a null stringNullPointerException: Cannot invoke "String.equals(Object)"With the literal first, there is no error: "yes".equals(answer).
Thinking substring's end is includeds.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
  1. rad 3 / 4 / -1 / 3345. toUpperCase()'s result is not assigned, so s is 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".
  2. true / false / true / true. "co" + "de" is a compile-time constant → the same object as the pooled a. c is a separate new object; d = c is the same reference. The contents match, so equals gives true.

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
  1. [Ali ][ 7][ 72,46]. %-5s: "Ali" + 2 spaces; %3d: 2 spaces + "7"; %7.2f: "72,46" (rounded) with 2 leading spaces.
  2. S.K. / student / giresun.edu.tr. char + "." is a string, so this is concatenation (two chars would add up to a number). @ is at index 7: substring(0, 7) and substring(8).

Summary

Exercises (1)

  1. Write reverse(String s): reverse("Giresun") → "nuseriG".
  2. count(String s, char target): returns how many times the character occurs. count("Karadeniz", 'a') → ?
  3. 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)

  1. "Object oriented programming with Java": how many words? Find out in one line.
  2. Write a program that counts the vowels in a word. "Ordu" → ?
  3. Ask for the age, then the full name, and print “Name: …, Age: …” with printf, avoiding the nextInt trap.
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);
Console
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).

The End

Chapter 3.4: Strings
Previous: Chapter 3.3: Arrays · Next: Chapter 3.5: Recursion
1 / 1 Sercan KÜLCÜ. All rights reserved.