i am very skeptical about s3==s4 returning a true. The equals will return a 'true' but == will not to my understnding of strings.
Here you are creating string literals...
When you are creating strin literals..there is an implicit call of intern fucntion...that checks whether there exists a string literal in the string pool that is the same as the one you are trying to create now...
If there exists one...then the reference of the same is returned...
A new string literal is not created...so both the references point to the same string literal reference
But if you are creating objects using new...then intern is not invoked implicitly...so 2 objects are created with same contents...
*literal strings will represent the same reference if they are created 1)in the same class and in the same package 2)in different classes within the same package 3)in different classes in different packages 4)using constant expressions computed at compile time by explicitly using the intern() method and the resulting string is already in the string pool
*literal strings will represent different references if they are newly created at runtime
The following example helps some how... (and it shows how to use intern() method explicitly)
String str1 = "Lions and Tigers and Bears!"; String str2 = "Lions and Tigers and Bears!"; String str3 = str2; String str4 = new String("Lions and Tigers and Bears!"); String str5 = " Oh my!"; String str6 = "Lions and Tigers and Bears! Oh my!"; String str7 = str1 + str5; String str8 = (str1 +" Oh my!").intern();
Comparison output: str1 == str2 -> true // the str2 literal existed ("interned") str1 == str3 -> true // hold the same reference str1 == str4 -> false // str4 explicitly created str2 == str3 -> true // hold the same reference str2 == str4 -> false // str4 explicitly created str3 == str4 -> false // str4 explicitly created str6 == str7 -> false // str7 computed at runtime str6 == str8 -> true // explicit use of intern() at runtim
Joined: Jul 10, 2001
thanks to both above posters.
This cert preparation is giving me new feel about the language(after many years of actual coding).