Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

String equals and == .... difference

DevenMay 10 2011 — edited May 10 2011
Hi All,

As per my understanding String equals matches the value of String and "==" matches objects represented on either side of the operator. but I saw some strange behavior while playing with these String API's.

class StringTest1
{
public static void main(String[] args)
{
String ja = "Ja";
String va = "va";

String java2 = "Java";
String java1 = ja + va;
//String java1 = "Java";

System.out.println("equals: " + (java1.equals(java2)));
System.out.println("==: " + (java1 == java2));
}
}

For the above code I get output as "true" for the first and "false" for the second expression. output of equals is fair enough but for "==" operator its giving false which as per my thinking should be true as the funda of String pooling says NO TWO STRINGS WITH SAME VALUES.
Among the 2 variables java2 is a string "Java" and java1 is a result of concatenation smthing like "Ja" + "va".

I tried to do something like
System.out.println("obj1: " + java1.hashCode());
System.out.println("obj1: " + java2.hashCode());
btu that returned the same value.

Please help me understand how come the expression be false for "==".

Edited by: 807216 on May 10, 2011 2:20 AM
This post has been answered by 802316 on May 10 2011
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 7 2011
Added on May 10 2011
20 comments
943 views