String class immutable. You can not change its state once after
creation. String str=new String("java"); This line creates object of
string "java" . You have again this time str=new String("core"); So be
clear that it does not assign this value to the previous object(having
"java" value) instead it creates new object and assigns "java" value.
Now str will point only new object which we have created recently having
"java" value. An object having "core" value is unreachable , it may get
garbage collected when gc will run. This is the reason string is called
immutable.
Following could be the reason of string immutability :
Following could be the reason of string immutability :
- Mostly we use string value parameter to pass to another method.
- Classloader uses string type to load the classes.
- String could cache its own hash code.
No comments:
Post a Comment