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.
“B”
if (h1.equals(h2)){ //gives a boolean and it is a best practise.
The Answer is B.
Note that h2.equals(h1) will give the same results since the equals method is symmetric.
Also note that h1 == h2 would be a valid way to compare the two Strings if h2 had been defined as:
String h2 = “Bob”;
since h2 would reference the same “Bob” String object from the JVM’s String pool.
However, this wouldn’t be the best practice. Always you the equals() method to compare Strings.
use*
Very few websites that come about to be detailed below, from our point of view are undoubtedly effectively worth checking out.
Always a huge fan of linking to bloggers that I enjoy but do not get lots of link appreciate from.