What is the output??(Easy One)

String s1="Java";
String s2="Java";
String s3=new String("Java");
String s4=new String("Java");
if(s1==s2)  System.out.print("true");
else  System.out.println("false");
if(s3==s4)  System.out.print("true");
else  System.out.println("false");
if(s1==s3)  System.out.print("true");
else  System.out.println("false");
if(s2==s3.intern())  System.out.print("true");
else  System.out.println("false");
if(s3.intern()==s2.intern())  System.out.print("true");
else  System.out.println("false");

Just try and get the Ouput---(Ignore any errors)

  1. true false true false true

  2. true false false true true

  3. true false false false true

  4. true false true false false


Correct Option: B

AI Explanation

To determine the output of the given code, let's go through each line step by step:

String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
String s4 = new String("Java");

In the above code, s1 and s2 are string literals, while s3 and s4 are objects created using the new keyword.

if(s1 == s2)
    System.out.print("true");
else
    System.out.println("false");

Here, s1 and s2 are both string literals, and they refer to the same object in the string pool. So, the condition s1 == s2 is true, and "true" is printed.

if(s3 == s4)
    System.out.print("true");
else
    System.out.println("false");

In this case, s3 and s4 are two different objects created using the new keyword, so the condition s3 == s4 is false, and "false" is printed.

if(s1 == s3)
    System.out.print("true");
else
    System.out.println("false");

Here, s1 is a string literal and s3 is an object created using the new keyword. They are not the same object, so the condition s1 == s3 is false, and "false" is printed.

if(s2 == s3.intern())
    System.out.print("true");
else
    System.out.println("false");

The intern() method returns the canonical representation of a string object from the string pool. In this case, s3 is interned and refers to the same object as s2. So, the condition s2 == s3.intern() is true, and "true" is printed.

if(s3.intern() == s2.intern())
    System.out.print("true");
else
    System.out.println("false");

Since both s3 and s2 are interned and refer to the same object in the string pool, the condition s3.intern() == s2.intern() is true, and "true" is printed.

Therefore, the output of the given code is:

B. true false false true true

Find more quizzes: