Multiple choice

What is the output of the 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);

  1. They matchThey really match

  2. They really match

  3. They match

  4. Nothing will be printed

  5. Compilation fails

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

The strings are not the same objects. So, the == comparison fails. As the values of the strings are the same, equals is true. The equals method compares values for equality. == compares references, not values. The use of == with object references is generally limited to the following: Comparing to see if a reference is null.