Java - String overview-interview
Q1. What is a String in Java?
A String in Java is an object of the String class used to represent a sequence of characters. Unlike arrays, it has built-in methods for manipulation.
Q2. Why are Strings immutable in Java?
Strings are immutable because:
- They are stored in the String Pool for memory efficiency.
- Immutability ensures security, thread-safety, and caching benefits.
Q3. What is the difference between == and .equals() when comparing Strings?
- == → Compares references (memory addresses).
- .equals() → Compares values (actual content of the String).
Q4. What is the difference between String, StringBuilder, and StringBuffer?
- String → Immutable.
- StringBuilder → Mutable, faster, not thread-safe.
- StringBuffer → Mutable, thread-safe, slightly slower due to synchronization.
Q5. What is the String Pool in Java?
The String Pool (or String Intern Pool) is a special area in the heap memory where Java stores string literals.
- If a string with the same value already exists in the pool, the new reference points to the existing object (saves memory).