Skip to the page

Objects and language basics · core

Strings: the pool, equals and building text

A String is immutable. Literals share one pooled object, so == works by luck. Use equals for content and StringBuilder when you build text in a loop.

The notes

What you must know

  • == compares references; equals compares text. Two equal literals are the same pooled object, so "hello" == "hello" is true.
  • new String("hello") creates a separate heap object, so == with the literal is false. intern() returns the pooled object.
  • Two literals joined with + are a compile-time constant and are pooled. With final String part = "hel", part + "lo" is also a constant. A non-final variable gives a new object at runtime.
  • Strings from user input, a database or JSON are never pooled. Always use equals, or Objects.equals when a value can be null.
  • The pool is in the normal heap since Java 7, so pooled strings are garbage-collected like other objects.
  • Compact strings (Java 9): Latin-1 text uses one byte per character, which halves memory for most strings.
  • s += x in a loop copies the whole string on every step, so the work grows with the square of the row count. Four times the rows is about sixteen times the time.
  • StringBuilder keeps one growing buffer. StringBuffer is the same but synchronized, so it does not help here. Better still, write through a BufferedWriter and do not hold the whole file in memory.

The red pen

Common traps: mistake → fix

  • Mistake: Using == on strings is fine when the text looks the same

    Fix: it works only for pooled objects; use equals.

  • Mistake: StringBuffer fixes slow concatenation

    Fix: it is only a synchronized StringBuilder; the cost is the repeated copying.

  • Mistake: Java 9 made += in a loop fast

    Fix: one a + b + c expression is compiled efficiently, but each loop pass still makes a new copy.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does a == b print for two equal string literals, and why?
  2. What is the difference between new String("x") and a literal?
  3. Why is s += row in a loop slow?
  4. A nightly job went from 5 minutes to 3 hours when data grew four times. How do you find the cause?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview