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?
Answer
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.
No comments:
Post a Comment