1
visibility

What will be the output of below statements?

String s1 = “Cat”;
String s2 = “Cat”;
String s3 = new String(“Cat”);
System.out.print(s1 == s2);
System.out.print(s1 == s3);

  • A

    truefalse

  • B

    truetrue

  • C

    falsefalse

  • D

    falsetrue

When we use double quotes to create a String, it first looks for String with the same value in the String pool. If found, then it returns the reference else it creates a new String in the pool and then returns the reference.

However using new operator, we force String class to create a new String object in heap space. So s1 and s2 will have reference to the same String in the pool whereas s3 will be a different object outside the pool, hence the output.