nerdexam
Oracle

1Z0-811 · Question #31

Given the code fragment: String s1 = "foo-bar"; String s2 = new String ("foo-bar"); System.out.print (s1.equals(s2) + " "); System.out.print (s1 == s2); System.out.print (" " + s1.compareTo (s2))…

The correct answer is B. true false 0. Option B is correct because equals() compares string content (both hold "foo-bar", so true), == compares object references (they point to different memory locations, so false), and compareTo() measures lexicographic difference - identical strings yield 0. A is wrong because…

Data Types and Operators

Question

Given the code fragment: String s1 = "foo-bar"; String s2 = new String ("foo-bar"); System.out.print (s1.equals(s2) + " "); System.out.print (s1 == s2); System.out.print (" " + s1.compareTo (s2)); What is the result?

Options

  • Afalse false -1
  • Btrue false 0
  • Ctrue true 0
  • Dfalse true -1

How the community answered

(17 responses)
  • A
    6% (1)
  • B
    94% (16)

Explanation

Option B is correct because equals() compares string content (both hold "foo-bar", so true), == compares object references (they point to different memory locations, so false), and compareTo() measures lexicographic difference - identical strings yield 0.

A is wrong because equals() returns true (same content), not false, and compareTo() returns 0, not -1. C is wrong because new String("foo-bar") explicitly allocates a new heap object, so s1 == s2 is false even though the content matches - this bypasses the String pool entirely. D is wrong on both equals() (content is identical → true) and == (different objects → false).

Memory tip: Think of == as asking "same object?" and equals() as asking "same value?" - and remember that new String(...) is the one keyword that guarantees a fresh object, making == fail even when content is equal.

Topics

#String equality#== vs .equals()#String methods#Reference comparison

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice