What is the best way to test that the values of h1 and h2 are the same?

Given the code fragment:
<code>
String h1 = “Bob”;
String h2 = new String (“Bob”);
</code>
What is the best way to test that the values of h1 and h2 are the same?

Given the code fragment:

String h1 = "Bob";
String h2 = new String ("Bob");

What is the best way to test that the values of h1 and h2 are the same?

A.
if (h1 == h2)

B.
if (h1.equals(h2))

C.
if (h1 = = h2)

D.
if (h1.same(h2))

Explanation:

The equals method compares values for equality.
Incorrect answers:
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 compares values for equality.
There is no generic comparison method named same.
= = (with a space) is not a valid method.

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 *