๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Immutable Strings in Java  


Introduction
  • In Java, String objects are immutable, meaning once a String object is created, its value cannot be changed or modified.
  • Any operation that appears to modify a String will always create a new object instead.
  • For example :-
    String s1 = "Hello";
    s1.concat(" World");     // Creates a new object, does not change s1
    System.out.println(s1);  // Output: Hello
  • Below is a diagram illustrating above example: Immutable Strings in Java

Why String Objects are Immutable?
  1. Shared References in String Pool:
    • Java stores string literals in a special memory area called the String Constant Pool (SCP).
    • Many variables can point to the same string object in the pool.
    • If strings were mutable (changeable), updating one reference would also change it for others.
    • To avoid this problem, String objects are made immutable.
  2. Security:
    • Strings are used to store important information like passwords, URLs and database connection details.
    • If strings could be changed, malicious code could modify this data and cause security issues.
    • Immutability ensures that once a string is created, its value is safe and cannot be altered.
  3. Caching & Reusability:
    • Because strings are immutable, the same String literal can be reused by different variables.
    • This avoids creating duplicate objects and helps in saving memory.
  4. Thread-Safety:
    • In multi-threaded programs, many threads can use the same String object at the same time.
    • Since the value of a string cannot change, it is automatically thread-safe.
  5. Performance in Hashing:
    • Strings are commonly used as keys in collections like HashMap and HashSet.
    • Because strings are immutable, their hashCode() value is always constant.
    • This makes searching and storing in HashMap or HashSet much faster and reliable.