-6

when i execute the code below, the output is "false"

String string1 = new String("ABC");  
String string2= new String("ABC");  
System.out.println(string1==string2);  

However the output when I don't use the string class's constructor is "true"

String string1;
String string2;
string1="ABC";
string2= "ABC";
System.out.println(string1==string2); 

I get that its better to use the .equals() methods but why the difference in output?

Rahul Bobhate
  • 4,892
  • 3
  • 25
  • 48

1 Answers1

1

Always use equals since == doesn't always work. Even though objects are the same in memory it may be stored in different places, and == checks for objects identity and not equality.

Michal Borek
  • 4,584
  • 2
  • 30
  • 40