Possible Duplicate:
Difference Between Equals and ==
In JDK 1.6, can String equals operation can be replaced with ==?
How do I compare strings in Java?
While playing around with Java-Strings, i did not expect the following results:
public class Sandbox {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
System.out.println(a == b); //true Why?, a and b both are seperate Objects
System.out.println(a == "hello"); //true Why?
System.out.println(a == new String(b)); //false As expected
}
}
I expected all to be false, since "==" compares references. Why this outcome?
When i change String b = "world"
, System.out.println(a == b);
returns false
. It seems as if the content of the String-Object is beeing compared.
Since Java 7 can compare Strings in switch-case-Statements, i thought it might have something to to with the Java-Version. But as described here, the equals-Methode is invoked when comparing Strings within a Switch-Case.