String and == Puzzles
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Interviewers love == on Strings because the same text can print true or false. In a written test or a live round they are checking that you know the difference between the same object and the same text, and can say why.
Compile-time constant folding vs runtime concatenation
String pool is a table kept by the JVM that holds one shared String object for each literal text, so two equal literals are the same object and == on them is true.
The program builds the text "Java" in four ways, then compares each one with the pooled literal using ==. Predict each result before you read the output.
Example 1 · Pooled, folded, runtime, interned
public class PoolDemo { public static void main(String[] args) { String a = "Java"; String b = "Ja" + "va"; // folded by the compiler String part = "Ja"; String c = part + "va"; // joined at runtime String d = c.intern(); // the pool's copy String e = new String("Java");
System.out.println("a == b: " + (a == b)); System.out.println("a == c: " + (a == c)); System.out.println("a == d: " + (a == d)); System.out.println("a == e: " + (a == e)); System.out.println("a.equals(c): " + a.equals(c) + ", a.equals(e): " + a.equals(e)); }}a == b: true a == c: false a == d: true a == e: false a.equals(c): true, a.equals(e): true
What this code does
"Ja" + "va"is folded into the literal "Java", so a and b are the same pooled object.partis not final, socis built at runtime as a new object;intern()returns the pooled one.equalsis true in every case.
Constant folding means the compiler joins constant expressions such as "Ja" + "va" while compiling, so the result is the pooled literal. A normal variable in the join makes it happen at runtime and creates a new object. The quick rules:
- Literal or literal + literal: pooled,
==istrue. - Variable + literal (not final): new object at runtime,
==isfalse. new String("x"): always a new object.s.intern(): the pool's copy,==istruewith the literal.
Predict the output
Same object or not?
Read each program and pick what it prints.
Round 1 of 3
A literal compared with a runtime join.
final String variables and the pool
A constant variable is a final variable of type String or a primitive that is set to a compile-time constant, such as final String ja = "Ja";. The compiler replaces it with its value, so a join using it is folded.
The program tests four + "va" == "Java" joins: a final local, a static final field, a normal variable and a final variable set by a method.
Example 2 · final constants fold, method results do not
public class FinalPoolDemo { static final String COURSE = "Ja";
static String prefix() { return "Ja"; }
public static void main(String[] args) { final String ja = "Ja"; String notFinal = "Ja"; final String fromMethod = prefix();
System.out.println("final local: " + (ja + "va" == "Java")); System.out.println("static final: " + (COURSE + "va" == "Java")); System.out.println("not final: " + (notFinal + "va" == "Java")); System.out.println("final, method: " + (fromMethod + "va" == "Java")); }}final local: true static final: true not final: false final, method: false
What this code does
jaandCOURSEare constant variables, so the compiler foldsja + "va"into the pooled literal "Java".fromMethodis final, but its value comes from a method call at runtime, so it is not a constant and the join makes a new object.
A static final constant behaves like a final local. The value must be known at compile time: final String ja = prefix(); is final but not a constant, because a method call runs only at runtime, so the join makes a new object.
Find the bug
Why is it false?
Each snippet should print true. Tap the line that stops it.
The label is built from a final variable but prints false.
Round 1 of 2replace, substring, toUpperCase without assignment
An immutable object never changes after it is created. A String is immutable, so methods such as toUpperCase() and trim() return a new String instead of changing the original.
Each call below looks like it edits name, but its result is thrown away. The StringBuilder lines near the end show a type that really does change.
Example 3 · String methods that seem to do nothing
public class ImmutableCallsDemo { public static void main(String[] args) { String name = " ravi kumar "; name.trim(); name.toUpperCase(); name.replace("ravi", "RAVI"); name.concat("!"); System.out.println("[" + name + "]");
name = name.trim().toUpperCase(); System.out.println("[" + name + "]");
String city = "Chennai"; String part = city.substring(0, 4); System.out.println(part + " " + city + " " + (part == "Chen") + " " + part.equals("Chen"));
StringBuilder sb = new StringBuilder("ravi"); sb.append("!"); sb.reverse(); System.out.println(sb);
System.out.println("banana".replace('a', 'o')); }}[ ravi kumar ] [RAVI KUMAR] Chen Chennai false true !ivar bonono
What this code does
- The four calls on separate lines each return a new String that nobody stores, so
nameis unchanged. Only the assignmentname = ...changes the variable. substringreturns a new object, so==with the literal is false whileequalsis true.StringBuildermethods change the builder itself.
Always assign the result: name = name.trim();. Methods such as substring also return new objects, so compare their results with equals, not ==.
Order of execution
What name = name.trim().toUpperCase() does
Tap the steps in the order Java runs them.
Wrapper == puzzles mixed with Strings
Integer cache is the set of Integer objects for -128 to 127 that Integer.valueOf, and so autoboxing, reuses. Boxing 127 twice gives one object; boxing 128 twice gives two separate objects.
The program boxes 127 and 128 twice each, then mixes Integer with int and Long. Notice which lines compare objects and which compare numbers.
Example 4 · Integer cache, unboxing and String conversions
public class WrapperPuzzleDemo { public static void main(String[] args) { Integer a = 127, b = 127; Integer c = 128, d = 128; System.out.println("127 == 127: " + (a == b)); System.out.println("128 == 128: " + (c == d)); System.out.println("128 equals: " + c.equals(d));
int plain = 128; System.out.println("Integer 128 == int 128: " + (c == plain));
Long big = 127L; System.out.println("Long.equals(127): " + big.equals(127)); System.out.println("Long.equals(127L): " + big.equals(127L));
String sa = String.valueOf(a); String sb = String.valueOf(b); System.out.println("\"127\" == \"127\" from valueOf: " + (sa == sb) + ", equals: " + sa.equals(sb)); }}127 == 127: true 128 == 128: false 128 equals: true Integer 128 == int 128: true Long.equals(127): false Long.equals(127L): true "127" == "127" from valueOf: false, equals: true
What this code does
- Autoboxing calls
Integer.valueOf, which returns cached objects from -128 to 127, so 127s share one object while 128s are two objects. - Comparing with an
intunboxes, so values are compared.Long.equalsneeds anotherLong; anInteger127 is never equal to it.
Unboxing means turning an Integer into an int. Integer == int unboxes and compares numbers, so it is true even for 128. Long.equals(127) is false, because 127 is boxed to an Integer, a different class, and String.valueOf always builds new Strings.
Predict the output
Integer: == or equals?
Read each program and pick what it prints.
Round 1 of 3
Two tickets numbered 127.
A checklist for any string puzzle
Run the checks below in order before you write an answer. The program then shows two traps they catch: + grouping before ==, and equals called on null.
- Is it
==orequals?==means same object. - Is every part a compile-time constant (literals,
finalconstant variables)? Then it is pooled. - Is a method's result thrown away? Strings never change in place.
- Is it a wrapper? Check the -128 to 127 cache, unboxing with a primitive, and the class in
equals. - Check
+precedence:"x: " + a == bcompares two Strings, not a and b. - Could anything be
null?s.equals("x")throws;"x".equals(s)andObjects.equalsdo not.
Example 5 · Precedence and null traps
import java.util.Objects;
public class StringTrapsDemo { public static void main(String[] args) { String a = "UPI"; String b = new String("UPI"); System.out.println("Equal: " + a == b); System.out.println("Equal: " + (a == b)); System.out.println("Equal: " + a.equals(b));
String input = null; System.out.println("UPI".equals(input)); System.out.println(Objects.equals(input, null)); try { System.out.println(input.equals("UPI")); } catch (NullPointerException e) { System.out.println("input.equals threw NullPointerException"); } }}false Equal: false Equal: true false true input.equals threw NullPointerException
What this code does
+binds tighter than==, so the first line compares the String "Equal: UPI" with b and prints justfalse.- Calling
equalson a constant ("UPI".equals(input)) or usingObjects.equalsis null-safe; calling it on a null variable throws.
Fix the error
Fix the error
Read the error, then pick the line that fixes it.
Round 1 of 2
This should print whether the fee is cleared.
Error
Fee.java:5: error: bad operand types for binary operator '==' first type: String second type: int
Next step
Check your understanding
12 quick questions