Thursday, July 19, 2018

== on String in Java not as expected?










I just got my first assessed coursework back with a mark of 97.14%, and the comment "When comparing strings you need to use the .equals() method of String == does not work the way you might expect."



How is == on Strings different, and if this is the case then why did my tests all work correctly anyway?



Answer



You got lucky. "==" compares the two objects to see what memory address they reference. It has nothing to do with what's actually in the string.



As pointed out in the comment below, if you're comparing two string constants, they may (will?) end up in the same memory location. So



String a = "abc";
String b = "abc";


In that case, (a == b) will return true. However if you force them into different memory locations with




String a = new String("abc");
String b = new String("abc");


then (a == b) will not return true.


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...