In Java, the String
class is immutable, means once a String
object is created, it cannot be changed. Any operation that seems to modify a string (like concat()
, replace()
, etc.) will instead create a new String object.
✅ Reasons Why String
is Immutable
1. ๐ Security
-
Strings are widely used in sensitive areas, like:
-
Network connections (
URL
,Socket
) -
File paths
-
Database credentials
-
Class loading (
Class.forName("com.example.MyClass")
)
-
-
If
String
were mutable, malicious code could change values after validation.
Example:
javaString className = "com.bank.Account";
Class.forName(className); // If mutable, could be changed to malicious class
2. ๐งต Thread Safety
-
Immutable objects are inherently thread-safe.
-
Multiple threads can access the same
String
object without synchronization.
3. ๐พ String Pooling (Interning)
-
Java maintains a String pool in the heap memory.
-
Immutability allows safe sharing of strings in memory:
javaString a = "hello"; String b = "hello"; System.out.println(a == b); // true — both refer to the same object
If String
were mutable, modifying a
would affect b
too — breaking pooling.
4. ๐ฏ Caching HashCode
-
String
'shashCode()
is used in HashMap, HashSet, etc. -
Since the content doesn't change, the hash can be calculated once and cached, improving performance.
5. ♻️ Consistent Behavior
-
You can safely pass strings between methods without worrying they’ll change:
javavoid printMessage(String msg) { System.out.println(msg); } printMessage("Hello"); // caller’s string remains unaffected
๐งช Internal Example
javaString s1 = "Java";
s1.concat(" Rocks!");
System.out.println(s1); // Output: Java
// Why? Because concat() returns a new object, not modifying s1
❗ If You Want Mutability
Use StringBuilder
or StringBuffer
:
javaStringBuilder sb = new StringBuilder("Java");
sb.append(" Rocks!");
System.out.println(sb.toString()); // Java Rocks!
๐ง Summary
Reason | Explanation |
---|---|
Security | Prevent tampering of sensitive strings |
Thread Safety | Safe for concurrent use without locking |
String Pooling | Reuse strings efficiently |
Hash Caching | Performance boost in collections |
Reliability | Strings behave consistently everywhere |
๐น Guidelines to Create an Immutable Class in Java
To create an immutable class, follow these rules:
Declare the class as final
→ Prevents subclasses from modifying behavior.
Declare all fields as private final
→ Prevents direct modification after initialization.
Do not provide setter methods
→ Ensures that fields cannot be modified.
Initialize fields only through the constructor
→ Provides controlled initialization.
Ensure defensive copying of mutable objects
→ Prevents external modification of internal mutable objects.
No comments:
Post a Comment