Chapter 11: Strings

Strings · Study Questions
String and charConcatenation (+)Index and charAtsubstring, indexOf, splitequals, ==, compareToStringBuilderApplications and printf
Sercan KÜLCÜ · Giresun University · Computer Engineering

Output Question · Basics

Question 1: "12" + "34"

What is the output of the following Java code?

String num1 = "12";
String num2 = "34";
String total = num1 + num2;
System.out.println(total);
int a = 12, b = 34;
System.out.println(a + b);
System.out.println(num1 + 3 + 4);
System.out.println(3 + 4 + num1);
Show answer

Output:

1234
46
1234
712
  • Between two Strings, + is concatenation: "12" + "34" = "1234" (even though the variable name is “total”).
  • Between two ints, + is addition: 46.
  • + is evaluated from left to right: "12" + 3 → "123", + 4 → "1234". On the other hand, 3 + 4 = 7 is added first, then "7" + "12" = "712".
"12"+"34"="1234"

Output Question · Basics

Question 2: char Arithmetic

What is the output of the following code? (The code of the character 'a' is 97.)

char k = 'a';
System.out.println(k + 1);
System.out.println((char) (k + 1));
System.out.println("" + k + 1);
System.out.println('a' + 'b');
Show answer

Output:

98
b
a1
195
  • A char is a number: k + 1 becomes an int → 97 + 1 = 98.
  • The (char) cast converts 98 to a character → b.
  • "" + k makes a String first ("a"), then "1" is appended → a1.
  • Adding two chars gives an int: 97 + 98 = 195 (not concatenation!).

Output Question · Basics

Question 3: Immutability

What is the output of the following code?

String s = "java";
s.toUpperCase();
s.concat("!");
System.out.println(s);
s = s.toUpperCase() + "?";
System.out.println(s);
Show answer

Output:

java
JAVA?
  • A String is immutable: toUpperCase() and concat return a new object; since the result is not assigned it is lost and s does not change.
  • On line 5 the new object that is returned is assigned to s: what changes is not the object but where s points.
"java"old object "JAVA"not assigned "JAVA?"s now points here

Output Question · Index

Question 4: charAt and indexOf

What is the output of the following code?

String s = "Giresun";
System.out.println(s.length() + " " + s.charAt(0) + s.charAt(s.length() - 1));
System.out.println(s.indexOf('e') + " " + s.indexOf("su") + " " + s.indexOf('x'));
System.out.println(s.charAt(2) + s.charAt(3));
0G1i2r3e4s5u6n
Show answer

Output:

7 Gn
3 4 -1
215
  • The last character is at index length() − 1 = 6: 'n'. Because the line starts with "7 ", the chars are concatenated.
  • indexOf gives the first position: 'e' → 3, "su" → 4 (the position of s); −1 if not found.
  • In the last line two chars are added: 'r' (114) + 'e' (101) = 215. For "re" you need "" + s.charAt(2) + s.charAt(3).

Multiple Choice · Index

Question 5: Out-of-Bounds charAt

What is the result of the call "Giresun".charAt(7)?

0G1i2r3e4s5u6nlast: 6

A: In a 7-character string the valid indices are 0–6. The compiler does not catch this; a StringIndexOutOfBoundsException is thrown at run time. A char is a primitive type, so it cannot return null.

Output Question · Methods

Question 6: substring Boundaries

What is the output of the following code?

String s = "PROGRAM";
System.out.println(s.substring(0, 3));
System.out.println(s.substring(3));
System.out.println(s.substring(2, 5) + "|" + s.substring(4, 4) + "|");
System.out.println(s.substring(1, 4).length());
0P1R2O3G4R5A6M2 included5 excluded →
Show answer

Output:

PRO
GRAM
OGR||
3
  • substring(a, b): a included, b excluded; the length is b − a.
  • One parameter: from the start index to the end → "GRAM".
  • substring(4, 4) is the empty string (not an error); the length of substring(1, 4) is 4 − 1 = 3.

Multiple Choice · Methods

Question 7: Faulty substring

String s = "PROGRAM";, which of the following causes a run-time error?

A: The valid range is 0 ≤ a ≤ b ≤ length(). Since 5 > 3, A causes an error. substring(7) and substring(3, 3) give the empty string, substring(0, 7) is the whole string.

Step-by-Step Trace · Methods

Question 8: First and Last Name from an Email

The first and last name are extracted from an email address. What are the variables after each line, and what is the output?

0e1c2e3.4k5a6y7a8@9u10n11i12.13t14r

A 15-character string; indices 0–14.

0e1c2e3.4k5a6y7a8@9u10n11i12.13t14rat = 8

indexOf('@') gives the index of the first @ character: 8.

0e1c2e3.4k5a6y7a8@9u10n11i12.13t14rexcluded

substring(0, 8): 0 included, 8 excluded → "ece.kaya" (8 characters).

0e1c2e3.4k5a6y7adot = 3

The search is now inside the user part: '.' is at index 3.

0e1c2e3.4k5a6y7a

substring(0, 3) → "ece".

0e1c2e3.4k5a6y7a

substring(4) → the part after the dot: "kaya".

toUpperCase() returns a new String; the variable last is still "kaya".

String s = "ece.kaya@uni.tr";
int at = s.indexOf('@');
String user = s.substring(0, at);
int dot = user.indexOf('.');
String first = user.substring(0, dot);
String last = user.substring(dot + 1);
System.out.println(last.toUpperCase() + ", " + first);

Multiple Choice · Methods

Question 9: split and the Empty Piece

What is "apple,pear,,cherry".split(",").length?

"apple""pear""""cherry"

C: The gap between two consecutive commas enters the array as an empty string (""): [apple, pear, , cherry] → 4. Only trailing empty pieces are discarded.

Output Question · Methods

Question 10: trim, replace, contains

What is the output of the following code?

String s = "  Ali Veli  ";
String t = s.trim();
System.out.println("[" + t + "] " + t.length());
System.out.println(t.replace('l', 'L'));
System.out.println(t.toLowerCase().contains("veli"));
System.out.println("banana".replace("an", "AN"));
Show answer

Output:

[Ali Veli] 8
ALi VeLi
true
bANANa
  • trim() removes only the leading and trailing spaces; the space in between stays → 8 characters.
  • replace replaces all matches and returns a new String.
  • "veli" is searched in lower case; because toLowerCase() is applied first, the result is true.

Output Question · Comparison

Question 11: == vs equals

What is the output of the following code?

String a = "Ordu";
String b = new String("Ordu");
String c = "Ordu";
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(b));
System.out.println(a == b.intern());
Show answer

Output:

false
true
true
true
  • a and c are the same object in the pool → true; new String is a separate object → a == b is false, but equals is true.
  • intern() returns the object in the pool → true.
acbOrduOrdu

Output Question · Comparison

Question 12: compareTo Values

What is the output of the following code? ('a' = 97, 'e' = 101, 'A' = 65)

System.out.println("egg".compareTo("apple"));
System.out.println("pen".compareTo("pencil"));
System.out.println("Ali".compareTo("ali"));
System.out.println("abc".compareTo("abc"));
Show answer

Output:

4
-3
-32
0
  • The code difference of the first differing character is returned: 'e' − 'a' = 101 − 97 = 4 (positive: egg comes later).
  • If one is the beginning of the other, the length difference: 3 − 6 = −3.
  • 'A' − 'a' = 65 − 97 = −32: upper-case letters come before lower-case ones.
  • Equal strings → 0.

Multiple Choice · Comparison

Question 13: equals with null

What happens when the following code is run?

String x = null;
System.out.println("const".equals(x));
System.out.println(x.equals("const"));

B: "const".equals(x) is a method of a real object; compared with null it returns false. x.equals(...) calls a method on null → NullPointerException. That is why the constant is written on the left.

Multiple Choice · Comparison

Question 14: Turkish Locale

What does "ISPARTA".toLowerCase(Locale.forLanguageTag("tr")) return?

C: In Turkish rules the lower case of capital I is the dotless ı. With an English locale it would be "isparta". The parameterless toLowerCase() depends on the machine's language; in technical text Locale.ENGLISH should be given.

Multiple Choice · Input

Question 15: nextLine() After next()

The user first types Ada and presses Enter, then types Giresun Merkez and presses Enter. What is the output?

Scanner k = new Scanner(System.in);
String word = k.next();
String line = k.nextLine();
System.out.println(word + "|" + line + "|");

D: next() reads "Ada" and the Enter (⏎) stays in the buffer. nextLine() reads up to ⏎ → returns the empty string, and the program continues before the user types the second line. Fix: put an extra k.nextLine(); in between.

Step-by-Step Trace · StringBuilder

Question 16: append, toString, reverse

What is the output of the following code? Follow the contents of sb step by step.

0a1b

The mutable buffer starts with "ab".

0a1b213-

append adds to the same object and returns the object itself; that is why it can be chained.

0a1b213-425-

No new String is created; the buffer grows.

0a1b213-425-637-

i = 3 was appended too.

4 <= 3 → false, the loop ends.

toString() produces a String that is separate from the current contents.

0-132-324-516b7a

reverse() reverses the buffer itself; s is not affected (a String is immutable).

When sb is concatenated with +, toString() is called automatically.

StringBuilder sb = new StringBuilder("ab");
for (int i = 1; i <= 3; i++) {
    sb.append(i).append('-');
}
String s = sb.toString();
sb.reverse();
System.out.println(s + " " + sb);

Multiple Choice · StringBuilder

Question 17: Cost of Concatenation in a Loop

Why is sb.append(i); preferred over s = s + i; in a loop?

A: Because a String is immutable, every + creates a new object; over n rounds the number of copied characters grows to about n²/2. StringBuilder is a mutable buffer, and a single toString() at the end is enough.

Step-by-Step Trace · Applications

Question 18: Caesar Cipher (shift = 2)

Each letter is shifted 2 positions forward in the alphabet. What is the output? (The position of a letter in the alphabet is c − 'a': a → 0, …, k → 10, z → 25)

0k1a2z

The result will be accumulated in a StringBuilder.

'k' − 'a' = 10; (10 + 2) % 26 = 12.

0m

'a' + 12 = 'm'.

0m1c

'a': (0 + 2) % 26 = 2 → 'c'.

'z': (25 + 2) % 26 = 27 % 26 = 1: % 26 wraps around to the start of the alphabet.

0m1c2b

'a' + 1 = 'b'.

To decrypt, the same loop is run with 26 − 2 = 24 instead of shift.

String text = "kaz";
int shift = 2;
StringBuilder cipher = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
    char c = text.charAt(i);
    int pos = (c - 'a' + shift) % 26;
    cipher.append((char) ('a' + pos));
}
System.out.println(cipher);

Multiple Choice · Applications

Question 19: Counting Words

What is the output of the following line?

String s = "  Ali ate  bread ";
System.out.println(s.trim().split(" +").length);

B: trim() removes the leading and trailing spaces; the regular expression " +" means “one or more spaces”, so a double space counts as a single separator → [Ali, ate, bread]. With split(" ") an empty piece would appear between the double spaces and the result would be 4.

Multiple Choice · Formatting

Question 20: Type Mismatch

What happens when the following line is run?

System.out.printf("%d%n", 3.5);

D: %d expects an integer, but a double was given. The compiler does not check the format string; the error occurs at run time. For a floating-point number use %f or %.1f.

The End

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