Practice mode Java

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.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.