String Immutability, the String Pool and == vs equals
45 min · Beginner
A Java String is an immutable object: once created, its text never changes. That one design choice explains the string pool, why == sometimes works by accident, and half the String puzzles in fresher interviews.
Topics in this lesson
- Recap: String is immutable and final
- Model answer: why String is immutable
- Literal vs new String(), and intern()
- Predict the output: == vs equals
- Traps: concat without assignment, == in conditions
Interview questions this lesson answers
- What does it mean that String is immutable?
- Is String a primitive type?
- Why is the String class final?
- What is the difference between
==andequalsfor strings? - What is the string pool?
- Why is String immutable? Give the main reasons.
- How does immutability help the string pool?
- How does immutability make strings good HashMap keys?
- Why is an immutable String thread-safe?
- How many objects does
String s = new String("abc");create?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.