Thursday, 19 July 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

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