Chapter 11: Strings

Computer Fundamentals and Introduction to Programming
StringIndexMethodsComparisonFormatting
Sercan KÜLCÜ · Giresun University

Introduction

Learning Outcomes

Representation

Explain the difference between String and char.

Processing

Use indices and the basic methods.

Comparison

Tell content comparison from reference comparison.

Output

Produce formatted text with printf.

Basics

What Is a String?

  • String is a java.lang class that represents a sequence of characters (no import needed).
  • String literals use double quotes ("Tarkan"), a char uses single quotes ('T').
  • String is not a primitive type but an immutable object; the variable holds a reference to it.
StackHeapname0T1a2r3k4a5nString object: char sequencec'T'char: value is on the stack

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; null refers to no object at all (none.length() → NullPointerException).
StackHeapString pool (literals)Tarkan""length 0Tarkannew: separatenameemptycopynonenull

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

String s = "Merhaba";

StackHeapMerhabaunchangedMerhaba!news

s = s + "!"; → a new object; the arrow moves to it, the old object is unchanged.

Basics · Step through the code

Immutability: toUpperCase()

StackHeapString pool (literals)javalang

lang refers to the "java" object in the pool.

StackHeapString pool (literals)javaJAVAno one refers to itlang

toUpperCase() produces a new "JAVA" object, but the result is assigned to nothing → it is lost. lang still refers to the old object.

StackHeapString pool (literals)javaJAVAgarbagelang

The old object is unchanged, so it prints java.

StackHeapString pool (literals)javaJAVAnew objectlang

This time the returned object is assigned to lang: the arrow moves to it. The "java" object is still intact.

StackHeapString pool (literals)javaJAVAlang

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

0G1i2r3e4s5u6nss.length() = 7s.charAt(0) → 'G's.charAt(6) → 'n'7✗
  • The first character is at index 0, the last at length() − 1; length() is a method (unlike the length field of arrays).
  • charAt(i) returns the char at that position; charAt(7) → StringIndexOutOfBoundsException.

Methods · Step through the code

Basic Methods

0J1a2v3a4␣5P6r7o8g9r10a11m12l13a14m15a

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

0J1a2v3a4␣5P6r7o8g9r10a11m12l13a14m15a

length() → 16; indices 0 … 15.

0J1a2v3a4␣5P6r7o8g9r10a11m12l13a14m15a▲ pos

indexOf gives the index of the first character of the match → 5 (−1 if absent).

0J1a2v3a4␣5P6r7o8g9r10a11m12l13a14m15a

substring(5, 16): 5 included, 16 excluded → 11 characters: "Programlama".

0J1a2v3a4␣5P6r7o8g9r10a11m12l13a14m15a

contains("Java") → true. No method changed s.

0J1a2v3a4␣5P6r7o8g9r10a11m12l13a14m15a

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

MethodResult
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
s0M1e2r3h4a5b6asubstring(1, 4) → "erh"indexOf('a') → 4length() → 7indexOf('z') → -1toLowerCase() → "merhaba"

Methods · Step through the code

split and replace Step by Step

0a1,2b3,4,5ctext0a1b2""3cp4 parts at the commas

split(",") cuts the text at the commas: "a", "b", "", "c". Between two adjacent commas is an empty string, and it stays in the array.

0a1b2""3cpp.length = 4

Arrays.toString(p) → [a, b, , c], p.length → 4. (Empty parts at the end are dropped: "a,b,,".split(",") gives only 2 parts.)

0a1l2i34v5e6l7is

s = "ali veli": 8 characters, a space at index 3.

0a1l2i34v5e6l7is0a1L2i34v5e6L7itreplace('l','L'): a new object

replace('l', 'L') turns every 'l' into 'L' (indices 1 and 6) and returns a new String; s is unchanged on this line.

0a1L2i34v5e6L7it

t is printed: aLi veLi.

0a1l2i34v5e6l7is

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 veli

Methods

replace, replaceAll, join, valueOf, format

CallResult
"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"

PROGRAM01234567s.substring(0, 3) → "PRO"

Think of indices as the lines between characters: between 0 and 3 is "PRO". Length = 3 − 0.

PROGRAM01234567s.substring(3, 7) → "GRAM"

The end may be length() = 7: the last character is included.

PROGRAM01234567s.substring(3) → "GRAM"

One-parameter version: from the start to the end.

PROGRAM01234567s.substring(2, 2) → ""

Start = end → the empty string "" (not an error).

PROGRAM01234567✗ no index 9s.substring(5, 9) → StringIndexOutOfBoundsException

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

0a1l2i3@4g5r6u7.8e9d10uemail

An 11-character email address; we will separate the user name and the domain.

0a1l2i3@4g5r6u7.8e9d10u▲ atemail

indexOf('@') → 3: the separator's position.

0a1l2i3@4g5r6u7.8e9d10u▲ atemail

substring(0, 3): 0 included, 3 (@) excluded → "ali".

0a1l2i3@4g5r6u7.8e9d10u▲ atemail

substring(4): from the character after @ to the end → "gru.edu".

0a1l2i3@4g5r6u7.8e9d10uemail

charAt(0) returns a char: 'a' (single quotes).

0a1l2i3@4g5r6u7.8e9d10uemail

The parts are joined and printed.

0a1l2i3@4g5r6u7.8e9d10uemail

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

StackHeapString pool (literals)Giresuna

The literal "Giresun" goes into the string pool; a refers to it.

StackHeapString pool (literals)GiresunGiresunseparate object (new)ab

new String(...) creates a separate object on the heap, even with the same contents.

StackHeapString pool (literals)GiresunGiresunseparate object (new)abc

The same literal again: the existing object in the pool is shared → c carries the same arrow as a.

StackHeapString pool (literals)GiresunGiresunseparate object (new)abc

a == b: the two arrows point to different objects → false (contents are ignored).

StackHeapString pool (literals)GiresunGiresunseparate object (new)abc

a == c: the two arrows point to the same object → true.

StackHeapString pool (literals)GiresunGiresunseparate object (new)abc

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

MethodPurposeExample
equalsContent equality"abc".equals("abc") → true
equalsIgnoreCaseEquality ignoring case"Java".equalsIgnoreCase("JAVA") → true
startsWithStarts with given text"Giresun".startsWith("Gir") → true
endsWithEnds with given text"Giresun".endsWith("sun") → true
compareToLexicographic 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.

GiresunstartsWith("Gir") → trueendsWith("sun") → trueequals("giresun") → falseequalsIgnoreCase("giresun") → true

Comparison · Step through the code

compareTo: Character and Length Differences

0e1l2m3ax

First x = "elma" (4 characters). The comparison uses the Unicode codes of these characters.

0e1l2m3ax0a1r2m3u4ty

y = "armut" (5 characters). The next line computes x.compareTo(y).

0e1l2m3ax0a1r2m3u4ty'e' (101) - 'a' (97) = 4

The first difference is at position 0: 'e' - 'a' = 101 - 97 = 4. Positive: "elma" comes after "armut" in the dictionary.

0k1e2d3ik

k = "kedi" (4 characters). Now let's see what happens when one string is a prefix of the other.

0k1e2d3ik0k1e2d3i4l5e6rargfirst 4 chars equal

k.compareTo("kediler"): the first 4 characters are the same and "kedi" ends; the result is the length difference.

0k1e2d3ik0k1e2d3i4l5e6rarg4 - 7 = -3 (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.ENGLISH for technical text such as keywords or file extensions, and Locale.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 ==.
StackHeapString pool (literals)GiresunsharedGiresunnewacb

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
Why?

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.

Null-safe comparison

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() or nextInt(), the ⏎ left in the buffer must be consumed by a separate nextLine().
Ada⏎Merhaba dünya⏎① next() → "Ada"③ nextLine() → "Merhaba dünya"② nextLine() → "" (only ⏎ is consumed)buffer: Ada⏎Merhaba dünya⏎⏎ = line end (Enter)

Input · Step through the code

Code Trace: next() and nextLine()

Keyboard buffer (System.in)▲ read position

The Scanner attaches to the keyboard stream; the buffer is empty for now.

Keyboard buffer (System.in)Ada⏎▲ read position

next() finds nothing to read and waits. The user types Ada and presses Enter → "Ada⏎" enters the buffer.

Keyboard buffer (System.in)Ada⏎▲ read position

next() reads up to a space or line end → "Ada". The ⏎ stays in the buffer.

Keyboard buffer (System.in)Ada⏎▲ read position

nextLine() reads up to the ⏎ → returns "" (empty) and consumes the ⏎. The buffer is clean now.

Keyboard buffer (System.in)Ada⏎Giresun␣Merkez⏎▲ read position

The buffer is empty → nextLine() waits. The user types Giresun Merkez and presses Enter.

Keyboard buffer (System.in)Ada⏎Giresun␣Merkez⏎read position ▲

The whole line (spaces included) is read → "Giresun Merkez"; the ⏎ is consumed but not added to the result.

Keyboard buffer (System.in)Ada⏎Giresun␣Merkez⏎read position ▲

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 + x creates a new String on every pass and copies the old one.
  • StringBuilder is a mutable buffer: append adds to the same object.
  • toString() builds the final String from the buffer's current contents.
String + (in a loop)1␣garbage1␣2␣garbage1␣2␣3␣new objectStringBuilder1␣2␣3␣one object

Performance · Step through the code

Code Trace: Joining with StringBuilder

StackHeap""StringBuilder (mutable)text

An empty, mutable buffer is created.

StackHeap""StringBuilder (mutable)text

1 <= 3 → true

StackHeap1␣StringBuilder (mutable)text

append(1) and append(' ') add to the same object (no new String) → "1 ".

StackHeap1␣StringBuilder (mutable)text

i++ → 2 <= 3 → true

StackHeap1␣2␣StringBuilder (mutable)text

append(2) and append(' ') add to the same object (no new String) → "1 2 ".

StackHeap1␣2␣StringBuilder (mutable)text

i++ → 3 <= 3 → true

StackHeap1␣2␣3␣StringBuilder (mutable)text

append(3) and append(' ') add to the same object (no new String) → "1 2 3 ".

StackHeap1␣2␣3␣StringBuilder (mutable)text

i++ → 4 <= 3 → false: the loop ends.

StackHeap1␣2␣3␣StringBuilder (mutable)1␣2␣3␣Stringtextresult

toString() builds a single String from the buffer.

StackHeap1␣2␣3␣StringBuilder (mutable)1␣2␣3␣Stringtextresult

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

0J1a2v3asrev""

We read the string from end to start and append to a new string.

0J1a2v3asrev""

Start with the empty string.

0J1a2v3a▲ isrev"a"

i = 3: append s.charAt(3) = 'a' → "a" (each += makes a new String).

0J1a2v3a▲ isrev"av"

i = 2: append s.charAt(2) = 'v' → "av" (each += makes a new String).

0J1a2v3a▲ isrev"ava"

i = 1: append s.charAt(1) = 'a' → "ava" (each += makes a new String).

0J1a2v3a▲ isrev"avaJ"

i = 0: append s.charAt(0) = 'J' → "avaJ" (each += makes a new String).

0J1a2v3asrev"avaJ"

i = −1 → the loop ends; the result is printed.

0J1a2v3ast2"avaJ"

Shortcut: StringBuilder's built-in reverse() gives the same result.

0J1a2v3ast2"avaJ"

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

0E1y2␣3E4d5i6p7␣8A9d10a11n12a13d14a15␣16p17i18d19e20␣21y22esentence

The sentence has uppercase letters and spaces; compared directly, 'E' ≠ 'e'.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18et

toLowerCase(tr) (Turkish rules) and replace(" ", "") → "eyedipadanadapideye" (19 characters).

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

Two end pointers: left = 0, right = 18. Assume isPal = true until proven otherwise.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'e' and 'e' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'y' and 'y' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'e' and 'e' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'd' and 'd' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'i' and 'i' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'p' and 'p' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'a' and 'a' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'd' and 'd' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ left▲ rightt

'a' and 'a' → equal; move inward.

0e1y2e3d4i5p6a7d8a9n10a11d12a13p14i15d16e17y18e▲ leftrightt

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

0m1e2r3h4a5b6a7␣8d9ü10n11y12ascount0

First the text is lowercased with Turkish rules (tr); the vowels string holds the Turkish vowels.

0m1e2r3h4a5b6a7␣8d9ü10n11y12ascount0

'm': indexOf → -1 → not a vowel.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓count1

'e': indexOf → 1 ≥ 0 → vowel, count = 1.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓count1

'r': indexOf → -1 → not a vowel.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓count1

'h': indexOf → -1 → not a vowel.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓count2

'a': indexOf → 0 ≥ 0 → vowel, count = 2.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓count2

'b': indexOf → -1 → not a vowel.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓count3

'a': indexOf → 0 ≥ 0 → vowel, count = 3.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓count3

'␣': indexOf → -1 → not a vowel.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓count3

'd': indexOf → -1 → not a vowel.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓✓count4

'ü': indexOf → 7 ≥ 0 → vowel, count = 4.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓✓count4

'n': indexOf → -1 → not a vowel.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓✓count4

'y': indexOf → -1 → not a vowel.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓✓✓count5

'a': indexOf → 0 ≥ 0 → vowel, count = 5.

0m1e2r3h4a5b6a7␣8d9ü10n11y12as✓✓✓✓✓count5

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)

0A1l2i3␣4␣5a6t7a8␣9b10a11ktextword0

A word is an unbroken run of non-space characters. We count the transitions from space to letter.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ newword1

'A' is a letter and we were outside a word → new word: word = 1.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ newword1

'l' continues the same word.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ newword1

'i' continues the same word.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ newword1

Space → we left the word.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ newword1

Another space (double space) → not counted.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ newword2

'a' is a letter and we were outside a word → new word: word = 2.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ newword2

't' continues the same word.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ newword2

'a' continues the same word.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ newword2

Space → we left the word.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ new▲ newword3

'b' is a letter and we were outside a word → new word: word = 3.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ new▲ newword3

'a' continues the same word.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ new▲ newword3

'k' continues the same word.

0A1l2i3␣4␣5a6t7a8␣9b10a11ktext▲ new▲ new▲ newword3

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])

skavaka0b0c0d0e0f0g0h0i0j0k0l0m0n0o0p0q0r0s0t0u0v0w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

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.

skavaka0b0c0d0e0f0g0h0i0j0k1l0m0n0o0p0q0r0s0t0u0v0w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

'k' - 'a' = 107 − 97 = 10 → freq[10] = 1.

skavaka1b0c0d0e0f0g0h0i0j0k1l0m0n0o0p0q0r0s0t0u0v0w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

'a' - 'a' = 97 − 97 = 0 → freq[0] = 1.

skavaka1b0c0d0e0f0g0h0i0j0k1l0m0n0o0p0q0r0s0t0u0v1w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

'v' - 'a' = 118 − 97 = 21 → freq[21] = 1.

skavaka2b0c0d0e0f0g0h0i0j0k1l0m0n0o0p0q0r0s0t0u0v1w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

'a' - 'a' = 97 − 97 = 0 → freq[0] = 2.

skavaka2b0c0d0e0f0g0h0i0j0k2l0m0n0o0p0q0r0s0t0u0v1w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

'k' - 'a' = 107 − 97 = 10 → freq[10] = 2.

skavaka2b0c0d0e0f0g0h0i0j0k2l0m0n0o0p0q0r0s0t0u0v1w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

k = 0: freq > 0 → (char) ('a' + 0) = 'a' is printed.

skavaka2b0c0d0e0f0g0h0i0j0k2l0m0n0o0p0q0r0s0t0u0v1w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

k = 10: freq > 0 → (char) ('a' + 10) = 'k' is printed.

skavaka2b0c0d0e0f0g0h0i0j0k2l0m0n0o0p0q0r0s0t0u0v1w0x0y0z0freq[0] = 'a' … freq[25] = 'z'

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

textenc0y1a2z3i4l5i6ma b c … x y zy + 3 → b (wraps around)

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.

textenc0y1a2z3i4l5i6mb+3a b c … x y zy + 3 → b (wraps around)

'y': (24 + 3) % 26 = 1 → 'b' (past 26, so % 26 wraps around).

textenc0y1a2z3i4l5i6mbd+3a b c … x y zy + 3 → b (wraps around)

'a': (0 + 3) % 26 = 3 → 'd'.

textenc0y1a2z3i4l5i6mbdc+3a b c … x y zy + 3 → b (wraps around)

'z': (25 + 3) % 26 = 2 → 'c' (past 26, so % 26 wraps around).

textenc0y1a2z3i4l5i6mbdcl+3a b c … x y zy + 3 → b (wraps around)

'i': (8 + 3) % 26 = 11 → 'l'.

textenc0y1a2z3i4l5i6mbdclo+3a b c … x y zy + 3 → b (wraps around)

'l': (11 + 3) % 26 = 14 → 'o'.

textenc0y1a2z3i4l5i6mbdclol+3a b c … x y zy + 3 → b (wraps around)

'i': (8 + 3) % 26 = 11 → 'l'.

textenc0y1a2z3i4l5i6mbdclolp+3a b c … x y zy + 3 → b (wraps around)

'm': (12 + 3) % 26 = 15 → 'p'.

textenc0y1a2z3i4l5i6mbdclolpa b c … x y zy + 3 → b (wraps around)

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␣%3d␣%7.2f%nformat stringargumentsname"Java"qty3price17.5output:Java␣␣␣␣left-aligned, width 8␣␣␣3␣␣␣17.50

%-8s ← name: "Java" is left-aligned in 8 cells; the other 4 are spaces.

%-8s␣%3d␣%7.2f%nformat stringargumentsname"Java"qty3price17.5output:Java␣␣␣␣␣␣␣3right-aligned, width 3␣␣␣17.50

%3d ← qty: the integer 3 is right-aligned in 3 cells.

%-8s␣%3d␣%7.2f%nformat stringargumentsname"Java"qty3price17.5output:Java␣␣␣␣␣␣␣3␣␣␣17.50width 7, 2 decimals

%7.2f ← price: "17.50" (5 characters, 2 decimals) is right-aligned in 7 cells.

%-8s␣%3d␣%7.2f%nformat stringargumentsname"Java"qty3price17.5output:Java␣␣␣␣␣␣␣3␣␣␣17.50⏎line end

%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.
"çay".length() = 3çayan emoji (e.g. smiling face): length() = 2← 1 visible characterD83DDE00← 2 chars (a UTF-16 pair)

Summary

Chapter Summary

Immutability

A String object is immutable; toUpperCase, + and substring return new objects.

Index

0 … length() − 1; substring(a, b): a included, b excluded, length b − a.

Comparison

equals for contents, compareTo for order; == compares only references.

Input / output

next reads a word, nextLine a line; StringBuilder for heavy concatenation, printf for formatting.

Summary

Review Questions

  1. Why is String called immutable?
  2. How does substring use its start and end bounds?
  3. What is the difference between == and equals?
  4. How do next and nextLine differ?
  5. Why might StringBuilder be preferred inside a loop?
Answers
  1. Once created, its characters cannot change; every “change” produces a new object.
  2. Start included, end excluded; the result length is end − start.
  3. == checks whether two variables refer to the same object, equals checks the characters.
  4. next stops at a space or line end and leaves the ⏎ in the buffer; nextLine reads the rest of the line and consumes the ⏎.
  5. It appends to a single buffer instead of creating and copying a new String on every pass.

Summary

Exercises

  1. Count the uppercase letters, lowercase letters, digits and spaces in a sentence separately.
  2. Check whether two words are anagrams (e.g. "elma" – "alem") using character frequencies.
  3. Print a full name entered by the user as "Surname, Name" with the surname in uppercase.
  4. Find the longest word in a sentence (with split).
  5. Extend the Caesar cipher to support uppercase letters (A–Z); leave other characters as they are.
  6. 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.

The End

Chapter 11: Strings
Previous: Chapter 10: Arrays · Next: Chapter 12: Recursion
1 / 1Sercan KÜLCÜ. All rights reserved.