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 == s2→falsebecausenew String("java")creates a new object in the heap. -
s2 == s3→truebecause both refer to the same string literal from the String Constant Pool. -
s1.equals(s3)→truebecause.equals()compares string content, not memory reference.
Author:
Trilochan Tarai
Founder, java8s.com & silanpay.com || Silan Software Pvt. Ltd.
No comments:
Post a Comment