Skip to lesson

String and == Puzzles

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.

Two variables, a and b, each point to their own String object with the text "Ravi". a == b is false because they are two different objects; a.equals(b) is true because the text is the same.

Example 1 · Pooled, folded, runtime, interned

PoolDemo.javaJava
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));    }}
Output
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.
  • part is not final, so c is built at runtime as a new object; intern() returns the pooled one. equals is 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, == is true.
  • Variable + literal (not final): new object at runtime, == is false.
  • new String("x"): always a new object.
  • s.intern(): the pool's copy, == is true with the literal.

Revise: String equals vs == (opens in a new tab).

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.

public class PoolRound1 {
public static void main(String[] args) {
String a = "Java";
String b = "Ja";
String c = b + "va";
System.out.println(a == c);
}
}

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

FinalPoolDemo.javaJava
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"));    }}
Output
final local:   true
static final:  true
not final:     false
final, method: false

What this code does

  • ja and COURSE are constant variables, so the compiler folds ja + "va" into the pooled literal "Java".
  • fromMethod is 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.

Revise: Constants and final (opens in a new tab).

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 2

replace, 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

ImmutableCallsDemo.javaJava
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'));    }}
Output
[  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 name is unchanged. Only the assignment name = ... changes the variable.
  • substring returns a new object, so == with the literal is false while equals is true. StringBuilder methods 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 ==.

Revise: Immutable objects (opens in a new tab).

Order of execution

What name = name.trim().toUpperCase() does

Tap the steps in the order Java runs them.

String name = " ravi ";
name = name.trim().toUpperCase();

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.

Left: Integer a = 100 and Integer b = 100 both point to the same cached Integer object, so a == b is true. Right: Integer c = 1000 and Integer d = 1000 point to two separate Integer objects, so c == d is false, although both hold the same number.

Example 4 · Integer cache, unboxing and String conversions

WrapperPuzzleDemo.javaJava
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));    }}
Output
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 int unboxes, so values are compared. Long.equals needs another Long; an Integer 127 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.

Revise: == compares references (opens in a new tab).

Predict the output

Integer: == or equals?

Read each program and pick what it prints.

Round 1 of 3

Two tickets numbered 127.

public class CacheRound1 {
public static void main(String[] args) {
Integer a = 127;
Integer b = 127;
System.out.println(a == b);
}
}

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.

  1. Is it == or equals? == means same object.
  2. Is every part a compile-time constant (literals, final constant variables)? Then it is pooled.
  3. Is a method's result thrown away? Strings never change in place.
  4. Is it a wrapper? Check the -128 to 127 cache, unboxing with a primitive, and the class in equals.
  5. Check + precedence: "x: " + a == b compares two Strings, not a and b.
  6. Could anything be null? s.equals("x") throws; "x".equals(s) and Objects.equals do not.

Example 5 · Precedence and null traps

StringTrapsDemo.javaJava
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");        }    }}
Output
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 just false.
  • Calling equals on a constant ("UPI".equals(input)) or using Objects.equals is 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.

public class Fee {
public static void main(String[] args) {
int paid = 500;
int due = 500;
System.out.println("Cleared: " + paid == due);
}
}

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