Given:
String message1 = “Wham bam!”;
String message2 = new String(“Wham bam!”);
if (message1 == message2)
System.out.println(“They match”);
if (message1.equals(message2))
System.out.println(“They really match”);
What is the result?
A.
They match
They really match
B.
They really match
C.
They match
D.
Nothing Prints
E.
They really match
They really match
Explanation:
The strings are not the same objects so the == comparison fails. See note #1 below. As the value of the strings are the same equals is true. The equals method compares values for equality.
Note: #1 ==
Compares references, not values. The use of == with object references is generally limited to the following:
Comparing to see if a reference is null.
Comparing two enum values. This works because there is only one object for each enum constant. You want to know if two references are to the same object.
“B”
Explanation:
String message2 = new String(“Wham bam!”);
if (message1 == message2) { … // false, because both hashCode() will be different.
This results : “B”
Correction:
String message1 = “Wham bam!”;
String message2 = “Wham bam!”;
if (message1 == message2) { … // true, because both hashCode() are same.
This results : “A”
Best Practise:
To use ” .equals ” to compare.
The Answer is B.
Ineed B, == compares the references and message2 has a new / another reference.