Wednesday, 7 September 2016

Why String is Immutable or Final in Java?

Immutable meaning :  cannot be changed.
JVM allocates the memory into parts, one is stack (for execution purpose) and the other is heap (for stoning objects).  And in heap JVM allocates some memory especially for string literals called as String constant pool.
String objects are cached in string pool. And these objects are shared between multiple clients. So there is a risk of operations made by one client effects the other clients too.
Reasons:
For security:   in the sense we pass the hostname, password as string as parameters. There is chance of changing these values if string is mutable.
Explanation:
When a string is created, an object is created inside heap memory as a string pool. 
Ex: string s1=”hello”;

If we create another string s2=”hello”,  s2 is referenced to value s1 is referencing, but when we change the value of s2 a new object is created and s2 is referenced to that, this happens because string is immutable, if string is not immutable then change s2 will also change the value of s1 which is not desired.

2 comments:

  1. PYTHON Report is a data-centric blog run by a speciality executive search firm called AUTOMATIONMINDS SOLUTION Partners. Whether you are
    an intermediate level data scientist or a pro, Data Science Report has got resources for all — it delivers resources from all variety
    of formats to help the reader in understanding data science properly.

    PYTHON Training in OMR Chennai

    ReplyDelete
  2. Great explanation! Your discussion on the immutability of strings in Java is clear and concise.
    Also Read: Java Performance Tuning: Optimizing Your Code for Speed

    ReplyDelete