What is the result?

Given:
<code>
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”);
</code>
What is the result?

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.



Leave a Reply 0

Your email address will not be published. Required fields are marked *