Strings: Practice Questions
Answers are hidden. Try each question before opening its answer.
Q1. Literal or new? Basic
Inside main:
String a = "Java";
String b = "Java";
String c = new String("Java");
System.out.println(a == b);
System.out.println(a == c);
System.out.println(a.equals(c)); What does this print?
Answer
true
false
true Why:
aandbcome from the same literal, so both point to the one"Java"object in the string pool.==compares references, and these are the same reference.new String("Java")always makes a new object on the heap, socis a different reference froma.equals()compares the characters, and all three hold"Java".
Remember: == asks “same object?”, equals() asks “same text?”. For strings you almost always mean equals().
Read more: String Constant Pool
Q2. The lost result Basic
String s = "hello";
s.toUpperCase();
s.concat(" world");
System.out.println(s); What does this print?
Answer
hello Why: strings are immutable. toUpperCase() and concat() don’t change s. Each one builds a new string and returns it. Here the returned strings are never stored, so they are thrown away and s still refers to "hello".
To keep the result, assign it: s = s.toUpperCase(); makes s refer to the new "HELLO" string. The old "hello" object is still unchanged.
Remember: a String method that “changes” the text always returns a new string. If you don’t use the return value, nothing happened.
Read more: Common Pitfalls
Q3. Changing one character Basic
String s = "java";
s.charAt(0) = 'J';
System.out.println(s); Does this compile? If not, how would you get "Java"?
Answer
No. The second line fails: you can’t assign to s.charAt(0).
Why: charAt(0) returns a char value (a copy of the character), not a slot inside the string. You can only assign to a variable, and a method call’s result isn’t one. Even if it were allowed, strings are immutable, so there’s no way to change a character in place.
Build a new string instead:
String fixed = Character.toUpperCase(s.charAt(0)) + s.substring(1); // "Java" Or copy the characters into an array, which is changeable, and make a new string from it:
char[] chars = s.toCharArray();
chars[0] = 'J';
System.out.println(new String(chars)); // Java
System.out.println(s); // java (the original is untouched) Read more: Basic Methods
Q4. Edges of substring Medium
String s = "Hello";
System.out.println("[" + s.substring(1, 4) + "]");
System.out.println("[" + s.substring(5) + "]");
System.out.println("[" + s.substring(2, 2) + "]");
System.out.println("[" + s.substring(6) + "]"); What does this print?
Answer
[ell]
[]
[] Then the last line throws StringIndexOutOfBoundsException.
Why: substring(start, end) takes the characters from start up to but not including end. The length of the result is end - start.
substring(1, 4)takes indexes 1, 2 and 3:"ell".substring(5)on a 5-character string starts at the end. That’s allowed and gives an empty string.substring(2, 2)has length2 - 2 = 0: an empty string.substring(6)starts past the end, so it throws.
Valid indexes for substring run from 0 to length(), both included. charAt is stricter: s.charAt(5) throws too, because there’s no character at index 5. Its valid indexes are 0 to length() - 1.
Remember: start is included, end is excluded, and length() is a legal boundary for substring but not for charAt.
Read more: Substring Methods
Q5. What compareTo returns Medium
System.out.println("apple".compareTo("banana"));
System.out.println("abc".compareTo("ab"));
System.out.println("Apple".compareTo("apple"));
System.out.println("apple".compareToIgnoreCase("APPLE")); What does this print?
Answer
-1
1
-32
0 Why: compareTo walks both strings from the start and stops at the first position where they differ.
- If the characters differ, it returns their difference:
'a' - 'b'is97 - 98 = -1. - If one string runs out first, it returns the difference in length:
"abc"vs"ab"gives3 - 2 = 1. 'A' - 'a'is65 - 97 = -32. Uppercase letters come before lowercase ones, so"Apple"sorts before"apple".compareToIgnoreCasetreatsAandaas equal, so the strings match:0.
Remember: only rely on the sign: negative means “comes before”, 0 means equal, positive means “comes after”. Code like if (a.compareTo(b) == -1) is a bug, because the result can be -32.
Read more: Comparison Methods, ASCII Values
Q6. The answer that’s never “yes” Medium
Scanner in = new Scanner(System.in);
String answer = in.nextLine();
if (answer == "yes") {
System.out.println("Saving...");
} else {
System.out.println("Cancelled");
} The user types yes. What does this print, and how do you fix it?
Answer
It prints Cancelled.
Why: the "yes" literal lives in the string pool. The string Scanner returns is built at runtime from the input, so it’s a different object, even though it holds the same characters. == compares references, so it’s false.
Fix it by comparing contents:
if ("yes".equals(answer)) { Putting the literal first is a common habit: if answer is null, "yes".equals(answer) is just false, while answer.equals("yes") throws a NullPointerException.
Remember: == on strings sometimes seems to work in tests that only use literals, then fails with real input. Use equals().
Read more: Common Pitfalls
Q7. + with numbers and strings Medium
System.out.println(1 + 2 + "3" + 4 + 5);
System.out.println("1" + (2 + 3));
System.out.println('a' + 'b' + "c");
System.out.println("c" + 'a' + 'b'); What does this print?
Answer
3345
15
195c
cab Why: + runs left to right. It adds numbers while both sides are numbers, and switches to joining text as soon as one side is a String.
1 + 2is3. Then3 + "3"is"33", and from there everything is joined as text:"334", then"3345".- The parentheses run first:
2 + 3is5, then"1" + 5is"15". 'a' + 'b'adds twochars, which is number addition:97 + 98 = 195. Then195 + "c"is"195c".- Starting with a string makes every
+join text:"ca", then"cab".
Remember: a char plus a char is an int, not a two-letter string. Start with "" or a string if you want text.
Read more: Type Conversion
Q8. When does + give a pooled string? Tricky
String s = "Java";
String part = "Ja";
final String fixed = "Ja";
System.out.println(s == "Ja" + "va");
System.out.println(s == part + "va");
System.out.println(s == fixed + "va"); What does this print?
Answer
true
false
true Why: it depends on whether the compiler can work out the result.
"Ja" + "va"joins two literals. That’s a compile-time constant: the compiler joins them itself and puts"Java"in the class file, so it’s the same pooled object ass.partis an ordinary variable, which could change before this line runs. Sopart + "va"is joined at runtime, which creates a new string object that isn’t in the pool.fixedisfinaland set from a literal, so it’s a constant too.fixed + "va"is joined at compile time, like the first line.
Remember: literals and constant expressions are pooled. Anything joined at runtime is a new object. One more reason never to compare strings with ==.
Read more: String Constant Pool
Q9. intern() Medium
String a = "Java";
String b = new String("Java");
String c = b.intern();
System.out.println(a == b);
System.out.println(a == c);
System.out.println(b == c); What does this print?
Answer
false
true
false Why: intern() looks for a string with the same contents in the pool. If there is one, it returns the pooled object. If not, it adds this string to the pool and returns it.
bis a separate heap object fromnew, soa == bisfalse."Java"is already in the pool (it’sa), sob.intern()returns that pooled object:cis the same reference asa.intern()doesn’t changeb. It still refers to its own heap object, sob == cisfalse.
Remember: intern() returns the pooled copy. It doesn’t turn the object you call it on into a pooled one.
Read more: String Constant Pool
Q10. How many objects? Tricky
String s = new String("Java"); How many String objects does this line create?
Answer
The new expression creates exactly one new object each time it runs. A second, pooled "Java" object exists too, but only if that literal wasn’t already in the pool, and it comes from the literal, not from new.
Why: the usual interview answer is “two”, and that’s only true in one case.
"Java"is a literal. The JVM makes sure there’s a pooledStringfor it. If the program has already used that literal (or any identical constant), the existing pooled object is reused and nothing new is made.new String(...)always makes a new heap object, copying the text from the pooled one.
So the first time this line runs with "Java" not yet in the pool, you end up with two objects: the pooled one and the new one. Every later run, or any run where "Java" was already pooled, makes only one.
In HotSpot (the usual JVM), the pooled object for a literal is created lazily, the first time the line that uses the literal runs, not when the class is loaded.
Remember: new makes one object. The pool only grows if the literal is new to it.
Read more: Heap Memory
Q11. Adding to null Tricky
String s = null;
s += "x";
System.out.println(s); Does this throw a NullPointerException? If not, what does it print?
Answer
No exception. It prints:
nullx Why: s += "x" means s = s + "x". When + joins strings, a null reference is turned into the text "null". No method is called on s, so there’s nothing to throw.
Compare that with s.concat("x"), which calls a method on s and throws a NullPointerException when s is null.
Remember: + on strings never throws for null, but it quietly puts the word null into your text. That’s usually a bug that’s harder to spot than an exception.
Read more: Common Pitfalls
Q12. Same object back? Tricky
String s = "Hello";
System.out.println(s == s.replace('z', 'w'));
System.out.println(s == s.replace('l', 'w'));
System.out.println(s == s.trim()); What does this print?
Answer
true
false
true Why: immutability means a method doesn’t have to make a new string when nothing changes. The Java documentation guarantees this for these two methods:
replace(char, char): if the old character doesn’t occur, it returns this same string. There’s no'z'in"Hello", so the result issitself.- There are
'l's to replace, so a new string"Hewwo"is made. trim(): if there’s no space at either end, it returns this same string.
This is safe only because strings are immutable: sharing an object is harmless when nobody can change it.
Remember: “string methods return a new string” means “they never change the old one”. It doesn’t promise a different object every time.
Read more: Modification Methods
Q13. Passing a string to a method Tricky
public static void main(String[] args) {
String s = "Java";
change(s);
System.out.println(s);
StringBuilder sb = new StringBuilder("Java");
change(sb);
System.out.println(sb);
}
static void change(String str) { str = str + "!"; }
static void change(StringBuilder sb) { sb.append("!"); } What does this print?
Answer
Java
Java! Why: Java passes everything by value. For objects, the value passed is a copy of the reference.
- In
change(String str),strstarts as a copy ofs’s reference.str + "!"builds a new string, andstr = ...points only the local copy at it.sinmainstill refers to"Java". And since strings are immutable, the method had no way to change the original object. StringBuilderis mutable.sb.append("!")changes the one object that both references point to, somainsees the change.
Remember: a method can change an object you pass in (if the object is mutable), but it can never make the caller’s variable point somewhere else.
Read more: Java Is Always Pass-by-Value
Q14. Building a string in a loop Medium
String s = "";
for (int i = 0; i < 100_000; i++) {
s += i;
} This works, but it’s slow. Why, and what should you use instead?
Answer
Each s += i creates a brand-new string and copies all the text so far into it. Use a StringBuilder.
Why: strings can’t grow in place. On every pass, Java builds a new String holding the old text plus the new number, and the old string becomes garbage. The text gets longer each time, so the total copying grows roughly with the square of the number of passes: 10 times more passes means about 100 times more copying.
A StringBuilder keeps one changeable buffer and adds to the end of it, so each append only copies the new part:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100_000; i++) {
sb.append(i);
}
String s = sb.toString(); + on a single line, like "Hi " + name + "!", is fine. The compiler already handles that efficiently. The problem is += repeated in a loop.
Remember: joining in a loop means StringBuilder.
Q15. Why are strings immutable? Medium
Give the main reasons Java’s designers made String immutable.
Answer
So that one string object can be shared safely: by the pool, by hash tables, by security checks and by threads.
Why: each reason relies on “nobody can change this string after it’s made”.
- The string pool: many variables share one pooled object (Q1). If one of them could change it, every other variable would see the change.
- Hash keys: strings are the most common
HashMapkey. A key whose contents changed after being added would be filed in the wrong place and become impossible to find. Because the text never changes, the hash code never changes either, soStringcan also compute it once and reuse it (OpenJDK does this). - Security: strings hold file paths, URLs and class names. If code checked a path and then used it, a mutable string could be changed in between, after the check passed.
- Threads: an object that can’t change can be shared between threads with no locking.
Remember: immutability is what makes sharing safe. When you need text that changes, use StringBuilder.
Read more: Creating Strings