String comparison with logical operator in Java

You shouldn’t use == because it does something else then you think.

In this case, the “hello” is saved (Read up on string interning), so it is “coincidence” that it is the same thing as your stirng.

== checks if two things are EXACTLY the same thing, not if they have the same content. This is a really big difference, and some accidental (though explainable) “false possitives” are no reason to use this method.

Just use equals for string comparison.

From this site an example:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

String a = new String ("a");
String b = new String ("a");
System.out.println (a == b);

It returns false, while the following code returns true.

String a = new String ("a");
String b = new String ("a");
System.out.println (a.equals(b));

Leave a Comment