When used on objects, == tests whether the two objects are the same object, not whether they have the same value. Consider this code fragment:

	String s1 = new String("Hello World");
	String s2 = new String("Hello World");
	if (s1 == s2) {
	  System.out.println("The strings are the same.");
	}
	else {
	  System.out.println("The strings are different.");
	}

This prints "The strings are different."

To compare to objects for equality, rather than identity, you should use the equals() method, like this:

	String s1 = new String("Hello World");
	String s2 = new String("Hello World");
	if (s1.equals(s2)) {
	  System.out.println("The strings are the same.");
	}
	else {
	  System.out.println("The strings are different.");
	}

This prints "The strings are the same." The default equals() method all objects inherit from java.lang.Object just tests for object identity with ==. However many classes, including java.lang.String, override equals() to test the state of the object.

However, the issue is a little confused when string literals are considered. Consider this code fragment:

	String s1 = "Hello World";
	String s2 = "Hello World";
	if (s1 == s2) {
	  System.out.println("The strings are the same");
	}
	else {
	  System.out.println("The strings are different");
	}

This prints "The strings are the same". The compiler recognizes that the two string literals have the same value and it performs a simple optimization of only creating one String object. Thus s1 and s2 both refer to the same object and are therefore equal. The Java Language Specification requires this behavior. However, not all compilers get this right so in practice this behavior here is implementation dependent.

Posted in: Java

Related FAQ's

Marius Ion ANGEL HOT SOFT LLC (800) 316-7677