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?

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 3

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


Jazz

Jazz

“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.

James

James

The Answer is B.

Hans

Hans

Ineed B, == compares the references and message2 has a new / another reference.