Wednesday 22 November 2017

Checking if strings are equal in java using ==





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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...