What is the output of the Java code String a = “hi”; String b = new String(“hi”); System.out.println((a == b) + ” ” + a.equals(b));?
Correct answer C. false true
Explanation
Using new always creates a distinct object, so == comparing the two references gives false even though their text matches. The equals method compares character content and gives true. For this reason strings should be compared with equals, while == should be reserved for checking whether two references point to the same object.
Answer checked How we write and check questions
Discussion