🔹 Introduction
One of the most commonly asked Core Java interview questions is:
👉 “Why is String immutable in Java?”
This question tests your understanding of:
- Memory management
- Security
- Performance
🔹 What Does Immutable Mean?
An immutable object is one whose state cannot be changed after creation.
👉 In Java:
-
Once a
Stringis created, it cannot be modified
🔹 Example
public class Test {
public static void main(String[] args) {
String str = "hello";
str.concat(" world");
System.out.println(str);
}
}
🔹 Output
hello
👉 Because original string is not modified
🔍 How String is Immutable Internally
-
Stringclass is final - Internal value stored in char array
- No setter methods
👉 Any modification creates a new object
🔹 Example with New Object
String str = "hello";
str = str.concat(" world");
System.out.println(str);
👉 Output:
hello world
🧠 String Constant Pool Concept
String a = "java";
String b = "java";
👉 Both refer to same memory location
👉 Saves memory
🔹 Why String is Immutable?
🥇 1. Security
-
Used in:
- Database URLs
- File paths
- Prevents modification
🥈 2. Thread Safety
- Immutable objects are thread-safe
- No synchronization needed
🥉 3. Performance (String Pool)
- Reuse existing objects
- Saves memory
🏅 4. HashMap Key Stability
- Used as keys in HashMap
- Ensures consistent hashCode
🔹 Time Complexity
- Depends on operation
- String creation → O(n)
🔹 Key Takeaways
✔ String is immutable
✔ Any change creates new object
✔ Improves security and performance
✔ Frequently asked interview question
🔹 Conclusion
String immutability is a core concept in Java and plays a crucial role in performance, security, and memory optimization.
Comments
Post a Comment