A String is a sequence of characters like “Hello” or “123”. In Java, String is a class, not a primitive type, and it’s used to store text.
1. What is the String Pool in Java?
The String Pool is a special area in memory where Java stores unique string literals. If you create two strings with the same literal:
String s1 = "Java"; String s2 = "Java";
They both point to the same object in the pool to save memory.
2. What is the difference between == and .equals() for strings?
== checks if two references point to the same object in memory. .equals() checks if the values inside the strings are the same.
Example:
String a = "Hello"; String b = new String("Hello"); System.out.println(a == b); //false System.out.println(a.equals(b)); //true
3. Are Strings mutable in Java?
No. Strings in Java are immutable, which means once you create a string, you can’t change its content. Any change creates a new string object.
4. Can you store two identical strings in the String Pool?
No. The pool stores only one copy of each unique literal string. If you write “Java” twice, both variables will point to the same object in the pool.
5. Using String Literal vs New Keyword
String s1 = "Java"; //Stored in String Pool String s2 = new String("Java"); //New object in Heap System.out.println(s1 == s2); //Output: false System.out.println(s1.equals(s2)); //Output: true
Explanation:
- s1 points to the “Java” in the pool.
- s2 creates a new object in the heap.
- == compares references → false
- .equals() compares values → true
6. Same String Literal
String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1 == s2); //Output: true
Explanation:
- Both s1 and s2 refer to the same literal “Hello” in the String Pool, so == returns true.
7. Assignment Between Strings
String s1 = "Hello"; String s2 = "Hello"; s1 = s2;
Explanation:
- This does nothing new. s1 and s2 already point to the same object in the String Pool.
- The assignment just confirms that s1 points to s2 — which it already did.