String immutability and equality
What you will learn
A String represents text whose content cannot change after creation. String operations produce results rather than editing the original. Use equals for text comparison and == only for reference identity.
public class Main { public static void main(String[] args) { String label = "box"; String saved = label; label = label + " 7"; System.out.println(saved); System.out.println(label); }}Expected output:
boxbox 7saved still refers to box.
How it works
String label = "box"; label = label + " 7"; assigns a different result to the variable; aliases still reach the old String. equals(Object) tests exact content and returns false for a null argument when the receiver is non-null. "ready".equals(status) works even if status is null. length() counts UTF-16 code units. isEmpty() checks for zero units, not whitespace. Concatenation with + associates left to right, so parentheses matter when mixing numbers and text. String literals may share identity; do not rely on that for content comparison.
public class Main { public static void main(String[] args) { String a = "ready"; String b = new String("ready"); String missing = null; System.out.println(a == b); System.out.println(a.equals(b)); System.out.println(a.equals(missing)); }}Expected output:
falsetruefalseThe explicit constructor creates a separate object with equal content.
Check a boundary or unusual input
public class Main { public static void main(String[] args) { System.out.println("".isEmpty()); System.out.println(" ".isEmpty()); System.out.println("Items: " + 2 + 3); System.out.println("Items: " + (2 + 3)); }}Expected output:
truefalseItems: 23Items: 5Without parentheses, the first concatenation produces text before the second addition.
Common mistakes
Do not ignore the result of a String transformation if you need the transformed value. Avoid calling methods on a possibly null receiver. Empty and null differ. Do not claim every operation must allocate a new String: immutable results may be reused when allowed.
Try it yourself
Write static boolean isReady(String status) returning true only for exact text ready; null, empty and different case must return false.
Save each example independently as Main.java; compile with javac --release 21 -encoding UTF-8 Main.java and launch using java Main. Local Java practice only; automatic ByteMind Java grading is not established.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
String immutability and equality — knowledge check
Practice core behavior and boundary cases.
What changes after s = s + "!"?
Which tests exact String content?
What does "ready".equals(null) return?
What does " ".isEmpty() return?
What is "N=" + 2 + 3?