Chapter 3.4: Strings

Chapter 3.4: Strings · Study Questions
Concatenationchar arithmeticIndexingMethodsImmutabilityStringBuilderScannerThe string poolcompareToprintf
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · The String Concept

Question 1: Order of Concatenation

What does System.out.println(1 + 2 + "3" + 4 * 5); print?

B: Multiplication comes first: 4 * 5 = 20. Then + is evaluated from left to right: 1 + 2 = 3 (two numbers), 3 + "3" = "33" (one side is a string, so it is concatenation), "33" + 20 = "3320". A concatenates the first two numbers as well; C forgets the precedence of multiplication and appends 4 and 5 separately.

Output Question · The String Concept

Question 2: Arithmetic with char

What does the program print? ('A' = 65, 'B' = 66)

char c = 'A';
System.out.println(c + 2);
System.out.println((char) (c + 2));
System.out.println("" + c + 2);
System.out.println(c + 'B' + "C");
System.out.println("" + 1 + 2 + '3');
Show answer
67
C
A2
131C
123
  • char + int is numeric addition: 65 + 2 = 67.
  • Converting the result with (char) gives the character with code 67: C.
  • With "" at the start, every + is concatenation: "A" + 2 = "A2".
  • c + 'B' is the sum of two chars (65 + 66 = 131); then "C" is appended.
  • "" + 1 = "1", + 2 = "12", + '3' = "123".

Output Question · The String Concept

Question 3: Indexing Backwards

What does the program print?

String s = "Giresun";
String t = "";
for (int i = s.length() - 1; i >= 0; i -= 2) {
  t += s.charAt(i);
}
System.out.println(t + " " + t.length());
System.out.println(s.substring(2, 5)
    + s.indexOf("sun") + s.indexOf('x'));
Show answer
nsrG 4
res4-1

The indices: G0 i1 r2 e3 s4 u5 n6. The loop reads indices 6, 4, 2, 0: n, s, r, G.

substring(2, 5) includes 2 and excludes 5: "res". "sun" starts at index 4; there is no 'x', so −1. Because "res" on the left is a string, 4 and −1 are not added as numbers but stick to the text: "res4-1".

Spot the Bug · The String Concept

Question 4: The Bound in a Backward Print

The code was written to print all the characters of the string from the end to the start, with a hyphen before each. What does the program print? Where is the bug?

String word = "Ada Kaya";
for (int i = word.length() - 1; i > 0; i--) {
  System.out.print("-" + word.charAt(i));
}
Show answer
-a-y-a-K- -a-d

The length is 8: indices A0 d1 a2 (space)3 K4 a5 y6 a7. The loop goes down from 7 to 1; because of the condition i > 0, the "A" at index 0 is not printed. The space is a character too: it shows up as "- ".

The fix: the condition should be i >= 0. The output becomes -a-y-a-K- -a-d-A.

Step-by-Step Trace · String Methods

Question 5: Splitting an Email Address

After each line, what are the indices and the parts? What does the program print?

ali.veli@giresun.edu.tr081620

23 characters; indices 0 … 22. The string will never change in the code: every method returns a new value.

ali.veli@giresun.edu.tr081620at

indexOf('@') is the index of the first @: 8 ("ali.veli" has 8 characters).

ali.veli@giresun.edu.tr081620atdot

The search starts at index 8: the dot at 3 is skipped, and the first dot is found at 16.

ali.veli@giresun.edu.tr081620at

substring(0, 8): 0 … 7, the end is excluded.

ali.veli@giresun.edu.tr081620atdot

substring(9, 16): what follows the @, up to the dot: 7 characters.

ali.veli@giresun.edu.tr081620last dot

lastIndexOf('.') = 20; substring(21) goes to the end: "tr".

ali.veli@giresun.edu.tr081620

replace('.', ' ') returns a new string; user is still "ali.veli".

String e = "ali.veli@giresun.edu.tr";
int at = e.indexOf('@');
int dot = e.indexOf('.', at);
String user = e.substring(0, at);
String domain = e.substring(at + 1, dot);
String extension = e.substring(e.lastIndexOf('.') + 1);
System.out.println(user.replace('.', ' ')
    + " " + domain + " " + extension);

Multiple Choice · String Methods

Question 6: substring and indexOf

What does the program print?

String s = "Java Programming";
System.out.println("[" + s.substring(5, 9) + "] "
    + s.indexOf("a", 2) + " "
    + s.lastIndexOf("am"));

D: "Program" starts at 5; substring(5, 9) takes indices 5, 6, 7, 8: "Prog" (the end is excluded, length 9 − 5 = 4). indexOf("a", 2) starts searching at index 2: the a at 1 is skipped, and 3 is found. "am" occurs only once, at 10 (a10 m11); lastIndexOf returns 10.

Output Question · String Methods

Question 7: split, trim and parseInt

What does the program print?

String s = " 3,apple, 12 ,pear ";
String[] p = s.trim().split(",");
System.out.println(p.length + " [" + p[2] + "]");
int total = Integer.parseInt(p[0])
    + Integer.parseInt(p[2].trim());
System.out.println(total + " "
    + String.join("-", p[1], p[3]));
System.out.println("Giresun".replace("e", "E")
    .toLowerCase().indexOf('e'));
Show answer
4 [ 12 ]
15 apple-pear
3

trim() removes only the leading and trailing spaces; split(",") does not touch the spaces inside the pieces: p = ["3", "apple", " 12 ", "pear"].

parseInt(" 12 ") would throw NumberFormatException; trim() is needed first: 3 + 12 = 15. In the last line, "GirEsun" turns back into "giresun" when lowercased; the first e is at index 3.

Output Question · String Methods

Question 8: Basic String Methods

Indices start at 0. What does the program print?

String s = "Programmer";
System.out.print(s.length() + " ");
System.out.print(s.charAt(4) + " ");
System.out.print(s.indexOf('r') + " ");
System.out.println(s.lastIndexOf("r"));
System.out.print(s.substring(3, 7) + "|");
System.out.println(s.substring(7));
System.out.print(s.equals("programmer") + " ");
System.out.println(
        s.equalsIgnoreCase("PROGRAMMER"));
System.out.print(s.indexOf("gram") + " ");
System.out.println(s.contains("pro"));
Show answer
10 r 1 9
gram|mer
false true
3 false
index0123456789
characterProgrammer
  • substring(3, 7): 3…6 (7 excluded) → "gram"; substring(7) goes to the end → "mer".
  • equals is case-sensitive; equalsIgnoreCase is not. contains("pro") is case-sensitive too: false.

Multiple Choice · Immutability

Question 9: Not Assigning the Result

What does the program print?

String s = "java";
s.toUpperCase();
s.concat("!");
String t = s.replace('a', 'o');
System.out.println(s + " " + t);

A: A String is immutable: toUpperCase() and concat("!") return new strings, but since the results are not assigned they are lost; s is still "java". The result of replace is assigned to t: "jovo". To make a change, write s = s.toUpperCase();.

Step-by-Step Trace · Immutability

Question 10: Tracing a StringBuilder

After each line, what are the contents of the buffer? What does the program print?

c0o1d2e3one object whose content can change

A mutable character buffer is created.

c0o1d2e34425!6append

append returns the same object, so calls can be chained. The number 42 is appended as "42".

J0a1v2a3·4c5o6d7e849210!11insert(0, …)

insert(0, "Java ") adds at the start; the old characters shift 5 places to the right.

J0a1v2a3·4C5o6d7e849210!11setCharAt(5, 'C')

The 'c' at index 5 becomes 'C' in place. With a String you could not write charAt(5) = 'C'.

J0a1v2a3·4C5o6d7e849!10deleteCharAt(10)

length() − 2 = 10: the '2' at index 10 is deleted; '!' shifts left.

!041e2d3o4C5·6a7v8a9J10reverse()

reverse reverses the buffer in place.

!041e2d3o4C5·6a7v8a9J10toString()

toString() makes a new String from the contents.

StringBuilder sb = new StringBuilder("code");
sb.append(42).append('!');
sb.insert(0, "Java ");
sb.setCharAt(5, 'C');
sb.deleteCharAt(sb.length() - 2);
sb.reverse();
String s = sb.toString();
System.out.println(s + " " + s.length());

Multiple Choice · Immutability

Question 11: Concatenating in a Loop

Why is concatenating n pieces in a loop with s += piece; slow?

C: Because a String is immutable, every += copies the old content and the new piece into a new object; the number of copied characters grows like 1 + 2 + … + n. StringBuilder.append grows the same buffer; the total work is O(n) on average. The pool holds only string literals (A); String has no such length limit (B).

Output Question · User Input

Question 12: nextInt, next and nextLine

The input typed on the keyboard is 25⏎Ali Veli Can⏎. What does the program print?

Scanner in = new Scanner(System.in);
int age = in.nextInt();
String a = in.nextLine();
String b = in.next();
String c = in.nextLine();
System.out.println("[" + a + "][" + b + "]["
    + c + "] " + age);
Show answer
[][Ali][ Veli Can] 25

nextInt() reads only the 25; the ⏎ after it stays in the buffer. The first nextLine() reads the empty text up to that ⏎: a = "".

next() reads one word: "Ali". The last nextLine() takes the rest of the line; the space after "Ali" is part of the line too: " Veli Can".

Multiple Choice · User Input

Question 13: next and nextLine

The input line is ␣␣␣hello world⏎ (three spaces at the start). After String a = in.next(); String b = in.nextLine();, what are a and b?

D: next() skips the leading spaces and reads up to the next space: "hello". nextLine() takes everything from where it left off to the end of the line; the space after "hello" is included. The ⏎ is consumed but does not become part of the result.

Step-by-Step Trace · Comparison

Question 14: The String Pool

After each line, which variable points to which object? What does the program print?

stackabcdefheapstring pool"code""co""de"

A literal gives a pool object; a points to "code" there.

stackabcdefheapstring pool"code""co""de"

"co" + "de" is constant: the compiler makes it "code"; b shares the pool object.

stackabcdefheapstring pool"code""co""de""code"

new always creates a new object outside the pool.

stackabcdefheapstring pool"code""co""de""code"

d = c copies the reference: both are the same object.

stackabcdefheapstring pool"code""co""de""code"

e points to "co" in the pool.

stackabcdefheapstring pool"code""co""de""code""code"

e is a variable: e + "de" is computed at run time into a new object.

stackabcdefheapstring pool"code""co""de""code""code"

== compares references: a, b share a pool object; c, d share a heap object.

stackabcdefheapstring pool"code""co""de""code""code"

f is another object with equal content; f.intern() returns its pool twin, a's object.

String a = "code";
String b = "co" + "de";
String c = new String("code");
String d = c;
String e = "co";
String f = e + "de";
System.out.println((a == b) + " " + (a == c) + " " + (c == d));
System.out.println((a == f) + " " + a.equals(f) + " " + (a == f.intern()));

Multiple Choice · Comparison

Question 15: compareTo

What do "plane".compareTo("plan") and "Plan".compareTo("plan") return, in that order? ('P' = 80, 'p' = 112)

A: "plan" is a prefix of "plane": there is no differing character, so the length difference is returned: 5 − 4 = 1 (positive: "plane" comes later). In the second, the first differing characters are 'P' and 'p': 80 − 112 = −32. Uppercase letters sort before lowercase ones.

Multiple Choice · Comparison

Question 16: Comparing with null

With String answer = null;, which of the following lines throws an exception?

C: A method cannot be called through a null reference: NullPointerException. In A and B the method is called on the literal; with a null argument it returns false. In D, concatenation turns null into the text "null": null!. This is why the literal is written first: "yes".equals(answer).

Output Question · Formatted Output

Question 17: printf Width and Precision

On a computer with the US locale, write out the output character by character.

System.out.printf("[%5s][%-6s][%04d][%6.2f][%.0f]%n",
    "abc", "de", 37, 3.14159, 2.5);
Show answer
[  abc][de    ][0037][  3.14][3]
  • %5s: 5 characters, right-aligned → ··abc.
  • %-6s: left-aligned, 4 spaces on the right → de····.
  • %04d: pads with zeros on the left → 0037.
  • %6.2f: 2 decimals, 6 characters in total; the separator is a period in the US locale → ··3.14.
  • %.0f: no decimals; Java rounds half up (HALF_UP): 2.5 → 3.

With a Turkish locale (tr-TR), the separator would be a comma: 3,14.

Multiple Choice · Formatted Output

Question 18: A Wrong Format Specifier

What happens when System.out.printf("%d%n", 3.5); is run?

B: To the compiler, the format string is ordinary text; a mismatch is noticed only at run time. %d wants integer types; for a double you need %f. printf does not convert, it throws an exception.

Multiple Choice · Applications

Question 19: The Middle Character

The method returns the middle character of a word (for an even length, the left one of the two middle characters). What do middle("Java") and middle("Giresun") return, and what happens on the call middle("")?

static char middle(String word) {
  int length = word.length();
  int middleIndex = length / 2;
  if (length % 2 == 0) {
    return word.charAt(middleIndex - 1);
  } else {
    return word.charAt(middleIndex);
  }
}

A: "Java" (J0 a1 v2 a3): the length 4 is even, middleIndex is 2, charAt(1) = 'a'. "Giresun" (G0 i1 r2 e3 s4 u5 n6): the length 7 is odd, charAt(3) = 'e'. On an empty string the length 0 counts as even and charAt(-1) is called: a run-time exception. The compiler does not know the values (D); Java has no "empty character" (B). The safeguard: an if (word.isEmpty()) check at the start.

Coding Question · Applications

Question 20: Counting Spaces

Write the method int countSpaces(String text) with charAt: it returns the number of space characters in the text.

  • What is countSpaces("Java is fun") (two consecutive spaces)?
  • What are countSpaces(" a b ") and countSpaces("")?
  • Why does text.split(" ").length - 1 not always give the right result?
Show answer
static int countSpaces(String text) {
  int count = 0;
  for (int i = 0; i < text.length(); i++) {
    if (text.charAt(i) == ' ') {
      count++;
    }
  }
  return count;
}

Results: 3, 3 and 0. charAt returns a char; it is compared with == against the single-quoted ' '.

split(" ") drops trailing empty pieces: " a b ".split(" ") → ["", "a", "b"], so the result is 3 − 1 = 2 (wrong). In the first example 3 comes out right: the method works by coincidence.

Coding Question · Applications

Question 21: A Palindrome Check

Write the method boolean isPalindrome(String s): it should ignore the difference between uppercase and lowercase and any non-letter characters (spaces, punctuation), and work with two indices without building a new string.

  • "A man, a plan, a canal: Panama" → true
  • "Kayak" → true
  • "Java" → false
Show answer
static boolean isPalindrome(String s) {
  int i = 0, j = s.length() - 1;
  while (i < j) {
    char a = s.charAt(i), b = s.charAt(j);
    if (!Character.isLetter(a)) i++;
    else if (!Character.isLetter(b)) j--;
    else if (Character.toLowerCase(a)
             != Character.toLowerCase(b))
      return false;
    else { i++; j--; }
  }
  return true;
}

Two indices move in from both ends; non-letters are skipped. char is primitive, so it is compared with !=. Output: true, true, false. No extra string is built; O(n).

The End

Chapter 3.4: Strings: Study Questions
Lecture slides: Chapter 3.4: Strings · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.