Thursday, 30 October 2025

Java String Handling – Placement Interview MCQ

 What will be the output of the following Java code snippet?

public class TestString {

    public static void main(String[] args) {

        String s1 = new String("java");

        String s2 = "java";

        String s3 = "java";

        System.out.println(s1 == s2);

        System.out.println(s2 == s3);

        System.out.println(s1.equals(s3));

    }

}

Answer: false, true, true

Explanation:

  • s1 == s2false because new String("java") creates a new object in the heap.

  • s2 == s3true because both refer to the same string literal from the String Constant Pool.

  • s1.equals(s3)true because .equals() compares string content, not memory reference.

Author:
Trilochan Tarai
Founder, java8s.com & silanpay.com  ||  Silan Software Pvt. Ltd.

No comments:

Post a Comment