nerdexam
Oracle

1Z0-803 · Question #12

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?

The correct answer is B. if (h1.equals(h2)). 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

Working with Selected Classes from the Java API

Question

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?

Options

  • Aif (h1 == h2)
  • Bif (h1.equals(h2))
  • Cif (h1 = = h2)
  • Dif (h1.same(h2))

How the community answered

(41 responses)
  • A
    5% (2)
  • B
    93% (38)
  • C
    2% (1)

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. 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 You want to know if two references are to the same object.

Topics

#string comparison#equals method#equality operator

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice