Why does this return true?
By the way... I'm teaching an introductory java course and I know everything about objects and memory allocation... I also know C, PHP, Assembly, Java, etc. I mention this so you don't start explaining me about objects and stuff like that :-)
String s1 = "hola";
String s2 = "hola";
if(s1 == s2) return true;
I just want to know why the code above returns true even though s1 and s2 are supposed to be 2 different String objects... I just don't get it. Is it a Java bug??
Never mind... I've found the answer:
When the java compiler finds two or more string "constants" that are equals, it points them to the same reference.
When you are creating String object like this.....String s1 = "hello";......then the compiler first checks in HEAP ....if same object is already there it points new to the existing one. But if you create like .... String s1 = new String("hello");.....it will always create a new String object.
Originally Posted by souFrag
intern() method is also there to check for existing Objects(new String("hello"))....in HEAP....
String s = "helo";
String s1 = new String("hello");
if(s == s1).......gives false
if(s == s1).......gives true
Compiler does this to save memory.
and == operator checks only references(two objects are pointing to the same Object) so it returns true.
This question was answered a few times before. It is always a good idea to search the forums for answers before you ask.
And the Google too. You can found lots of information regarding this. Most people confused with this each day.
Of course I tried searching :-)
But the only answers I found were "you must use equals() to compare Strings" and that was not my question... I wanted to know why sometimes using "==" to compare to String objects would return true even though they seemed to be different objects.
sanjeevtarar, thanks for your answer.