String stringG = "Red Delicious" ; // create a String literal, stringG points to it
String stringH = "Red Delicious" ; // point stringH to the same String literal
if (stringG == stringH)
System.out.println( "One Literal" );
else
System.out.println( "NOT Equal" );
One Literal
Recall that, as an optimization, only one object is made for string literals containing the same characters.
So in the above, both variables point to the same object.
The == returns true because
stringG and stringH
contain identical references.
When the new operator is used in
the previous version of this code, two individual objects
are constructed and == returns false.
equals MethodHere is another misleading situation:
class ArrayEquality
{
public static void main ( String[] args )
{
int[] arrayE = { 1, 2, 3, 4 };
int[] arrayF = { 1, 2, 3, 4 };
if (arrayE.equals( arrayF ) )
System.out.println( "Equal" );
else
System.out.println( "NOT Equal" );
}
}
Output:
NOT Equal
The equals() method for arrays returns the same boolean value as does ==.
Again,
the array object referred to by the variable arrayE is not the same
array object that is referred to by the variable arrayF.
The two objects look the same, but are different objects, and not equal.
Are there times when you would like a method that
examines two arrays (like the above two) and returns
true or false depending on the
elements of the arrays?