Tuesday, January 29, 2019

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...