What is displayed when the following code is compiled and executed? String s1 = new String("Test"); String s2 = new String("Test"); if (s1==s2) System.out.println("Same"); if (s1.equals(s2)) System.out.println("Equals");

  1. Same

  2. Equals

  3. The code compiles, but nothing is displayed upon execution.

  4. The code fails to compile


Correct Option: B

AI Explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) Same - This option is incorrect. The code does not print "Same" because the "==" operator compares the references of the two objects, not their actual content.

Option B) Equals - This option is correct. The code prints "Equals" because the ".equals()" method compares the content of the two objects, and since the content of both "s1" and "s2" is "Test", the condition is true and "Equals" is displayed.

Option C) The code compiles, but nothing is displayed upon execution - This option is incorrect. Something is displayed upon execution because the code contains print statements.

Option D) The code fails to compile - This option is incorrect. The code does compile successfully.

The correct answer is B) Equals. This option is correct because the ".equals()" method compares the content of the two strings, and since the content is the same, the condition is true and "Equals" is printed.

Find more quizzes: