Repaso
EspaƱol
Java CoreCoreJV-04

What does this print?

String a = new String("hi");
String b = new String("hi");
System.out.println((a == b) + " " + a.equals(b));

Options

  1. true true
  2. true false
  3. false true (Correct option)
  4. false false

Answer

false true

Why

For objects, == compares references: are both variables pointing to the exact same object in memory? new String(...) always creates a new object, so a == b is false.

.equals() compares the content. Both strings contain "hi", so it is true.

Rule: use .equals() to compare text and other objects; use == for primitives and for checking null.

Remember

== compares references, equals() compares content.

Key terms

Practice this question in Repaso