0

I found that this, but I don't know what the point.

String s1 = new String("heyheyhey");
String s2="heyheyhey";
String s3="heyheyhey";
if(s1==s2)System.out.println("s1 == s2");
if(s2==s3)System.out.println("s2 == s3");

Why different results for both if statements?

kurumkan
  • 2,635
  • 3
  • 31
  • 55

2 Answers2

0

String class: 1.when use new keyword means get a new memory site. 2.when use "" style means will try to get the workds from constant pool,if doesn't exist it will return new memory site.

Risk4U
  • 33
  • 7
0

== checks for the reference. .equals checks for the actual component.

In your case s1 and s2 are pointing to two different objects and s2 and s3 are sharing the common reference since there component is same.

Check out this question for detailed explanation.

Community
  • 1
  • 1
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78