Java Notes
Review the Java String concepts interviewers commonly test: immutability, the String Pool, equals versus ==, and choosing StringBuilder or StringBuffer.
These questions are not for memorising sentences. Answer each one by explaining what Java stores, what the code compares, and why that matters in a real program.
Why is String immutable?
An existing String cannot change; a changing method creates another value. Immutability makes pooled literals safe to share, supports thread-safe reading, and prevents a value used as a map key from changing after insertion.
What is the String Pool?
The String Pool is a shared area where Java can reuse literal String values. Two identical literals commonly point to the same object. An object created with new String("Java") is separate, even though it contains the same characters.
What is the difference between == and equals()?
== compares references: are both variables pointing at the same object? equals() compares character content. Text from input, files, databases, or APIs must be compared with equals() or equalsIgnoreCase().
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Run it, then explain: the first comparison asks about objects and the second asks about text.
String, StringBuilder, or StringBuffer?
| Type | Choose it when | Important property |
|---|---|---|
String | Text should not change | Immutable |
StringBuilder | You build text repeatedly in one thread | Mutable and faster for normal building |
StringBuffer | The same mutable buffer is shared across threads | Mutable and synchronised |
Can a String variable change?
The variable can be reassigned, but the String object cannot be edited. In name = name.toUpperCase(), the right side creates a new String and the variable then points to it.
Why should a loop use StringBuilder instead of +?
Repeated concatenation can create many temporary String objects. A StringBuilder keeps one mutable buffer and appends into it, so it is the clearer performance choice when the number of additions is large or unknown.
Continue the lesson path