Why is String Immutable

  1. Immutable – Unchangeable. Once initialized the values cannot be changed
  2. When tried to change it will create a new object
    1. String s= new String( ” Zoo “) ;s = s + “Keeper”;  The JVM will create 2 objects on the heap.  Once to store “Zoo” and another to store “Zoo Keeper”
  3. Primitive datatypes like int,long etc can also be made immutable by declaring it “final”
  4. They are thread-safe implicitly. Since threads cannot change the value no need to perform synchronization.
  5. Suitable to act as a “key” to HashMap  etc
  6. Immutable class can be created by
    1. Declaring the class final
    2. Or Use Static and define private Constructor
    3. Do not provide any method for changing the state of the object
  7. Hashcode of the String will always be the same and hence it can cached
  8. Strings are used in DB connection , Networking etc. If it is not mutable then it would lead to serious issue not connecting to the right DB etc

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Cheat Sheet To JAVA Latest Technology

%d bloggers like this: