Java String Interview Question


If we have the following in a Java code:

String s="abc"; 
String s2="abc";

Then what will be output of:

System.out.println("s.equals(s2) = "+s.equals(s2));
System.out.println("s==s2 = "+(s==s2));

✍: Guest


The correct answer is:

s.equals(s2) = true
s==s2 = true

The following answer is wrong. Because both literals of the same string are interned as a single object by the Java compiler, as pointed out by Kevin.

s.equals(s2) = true
s==s2 = false

2016-06-26, 11351👍, 2💬