WHY STRING IS IMMUTABLE IN JAVA

Here today I will Talk about the Two important Questions for the interview first one is.
  1. Why Strings are Immutable ? 
  2. What is the time Complexity of hash map ?
The First One we take why Strings are Immutable ?

This is the Question which is asked often why String is immutable ans is that in Java for String we have memory that is used is the String pool and a heap the heap contains the String pool. Now what is the use of String pool how it works is the other Question itself for the String pool as you write

Srting str="abc";

By writing this what is the backend process .?

By instantiating String and value Added is "abc" this is created in the  String pool just imagine that String pool is in the heap memory and it is a block in the heap memory a large block which contains storage of String literals i.e Constants.

First of all when we Write String str="abc" it checks in the pool whether the "abc" type of Sting is present or not if present than returns refrence else create the String there in the pool of "abc" and return a refrence. 

Now why the String pool is maintained in the Heap it is because it allows String to cache its hash code based on that the Hashmap uses its hash code so as String is immutable there are no worries to 
have its hashcode to be changed.

Other is that the replica is formed in the String pool So that whenever we want to access it gets faster to access SO the main purpose is to reduce the memory overhead just as to reduce the cost of read and write operations .

Now again the Interviever asks what if I Write String Str=new String("abc");  does it change the value or not ....????

The answer is yes the value gets changed as the by writing new it creates "abc" in the pool as well as in the heap so if we Write String str="abc" the literal is created in the pool now if we Write 

String Str=new String("pqr");

It generates pqr in the pool as well as in the heap but points the heap's "pqr" now again if we Write str="xyz" creates "xyz" in the pool.


Hope you might have got the idea as this is very important post for the concept in interviews comment below your Views about this post and any other question for which I could post here.
Will Discuss the second question in the next post.  

Comments

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another