JavaBeginner#puzzle#strings

What is the output of this code? String s1 = "abc"; String s2 = "abc"; String s3 = new String("abc"); System.out.println(s1 == s2); System.out.println(s1 == s3);

s1 and s2 both refer to the same interned literal in the String pool, so s1 == s2 is true. s3 is a new heap object, so s1 == s3 compares different references and is false.

Example
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false

Related Questions

1
JavaAdvanced#puzzle#exceptions

What does this code output and why? try { return 1; } finally { return 2; }

Open
2
JavaAdvanced#puzzle#collections

What is the output? List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); for (Integer i : list) { if (i == 1) list.remove(i); }

Open
3
JavaIntermediate#puzzle#oop

What is the output of this code involving static and instance initialization order? class A { static { System.out.println("static A"); } { System.out.println("instance A"); } A() { System.out.println("constructor A"); } } new A(); new A();

Open