We all known the equals() check the content of the string , but '= =' checks the object reference.
Strings are immutable and final in Java
Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method, It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality. Now if you are puzzled why String is immutable or final in Java.
Strings are maintained in String Pool
Advanced Java String tutorial and example programmers As I Said earlier String is special class in Java and all String literal e.g. "abc" (anything which is inside double quotes are String literal in Java) are maintained in a separate String pool, special memory location inside Java memory, more precisely inside PermGen Space. Any time you create a new String object using String literal, JVM first checks String pool and if an object with similar content available, than it returns that and doesn't create a new object. JVM doesn't perform String pool check if you create object using new operator.
String str = "John"; //1st String object
String str1 = "John"; //same Sring object assigned
String str2 = new String("John") //forcing JVM to create a new String object
//this will return true
if(str == str1){
System.out.println("both str and str1 are pointing to same string object");
}
//this will return false
if(str == str2){
System.out.println("both str and str2 are pointing to different string objects");
}
String str1 = "John"; //same Sring object assigned
String str2 = new String("John") //forcing JVM to create a new String object
//this will return true
if(str == str1){
System.out.println("both str and str1 are pointing to same string object");
}
//this will return false
if(str == str2){
System.out.println("both str and str2 are pointing to different string objects");
}
Please post comments !
No comments:
Post a Comment