Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison with logical operator in Java

When comparing two strings, I was taught that we shouldn't use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the following code complies and prints "Hello Friend" with the latest JDK(1.6_23). I tried searching around and couldn't find any reference. From when is this happening?

public class StringComp{
public static void main(String args[]){
        String s = "hello";
        if(s=="hello"){
                System.out.println("Hello Friend");
        }else{
                System.out.println("No Hello");
        }
    }
}
like image 412
Sundeep Avatar asked Dec 02 '22 03:12

Sundeep


2 Answers

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));
like image 181
Nanne Avatar answered Dec 23 '22 02:12

Nanne


The magic is called interning.

Java interns String literals and so there is a high probability that it evaluates to true:

String a = "hello";       // "hello" is assigned *and* interned
String b = "hello";       // b gets a reference to the interned literal
if (a == b)
   System.out.println("internd.");

String c = "hello" + Math.abs(1.0);   // result String is not interned
String d = "hello" + Math.abs(1.0);   // result String is not interned
System.out.println(c==d);             // prints "false"

c = c.intern();
System.out.println(c==d);             // prints "false"

d = d.intern();
System.out.println(c==d);             // prints "true"
like image 34
Andreas Dolk Avatar answered Dec 23 '22 03:12

Andreas Dolk