Why String is Immutable ?



Why String is immutable and final in Java?

 

when you define a string object . object creates in heap . value of this object can not be change. String

 str=new String("Shiv"); now str.concat("shakti"); if you print str . Output will be Shiv only. Not Shivshakti.

 But when you write str=new String("shakti"); print output will be shakti. This happens due to str change 

of reference to shakti object . Now if you write str=str.concat("shakti"); Output will be Shivshakti. This is

happens due to change reference but str value remains same Shiv. In case of shakti it create new object in heap.
        
Why String is Immutable ? Why String is Immutable ? Reviewed by Mukesh Jha on 3:58 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.