The easiest way of creating a String object is using a string literal:
String str1 = "You cannot change me!";
String str2 = "You cannot change me!";
here str1 and str2 holds the same String literal.
so at the Compile time java compiler optimizes handling of string literals(and compile-time constant
expressions that evaluate to strings)
so for the above two String str1 and str2 holds the same character sequence so they will be sharing a single string reference .these type of String are said to be "Interned".
The String class maintains a private pool where such strings are interned.
and if you call any methods on str2 wont effect the str1 reference.
String str3 = "You cannot" + "change me!";
this intern can be applied to str3 also
intern will not be applied to str5 so a new string will be created for str5.
and finally A string constructed with new operator will always creates a new reference in jvm.
String str1 = "You cannot change me!";
String str2 = "You cannot change me!";
here str1 and str2 holds the same String literal.
so at the Compile time java compiler optimizes handling of string literals(and compile-time constant
expressions that evaluate to strings)
so for the above two String str1 and str2 holds the same character sequence so they will be sharing a single string reference .these type of String are said to be "Interned".
The String class maintains a private pool where such strings are interned.
and if you call any methods on str2 wont effect the str1 reference.
String str3 = "You cannot" + "change me!";
this intern can be applied to str3 also
String s = "change me!";
String str5 = "You cannot" + s ;
intern will not be applied to str5 so a new string will be created for str5.
and finally A string constructed with new operator will always creates a new reference in jvm.
No comments:
Post a Comment