JAVA Programming :: Basic Concepts - Discussion
25 / 64
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = new String("abc");
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = new String("abc");
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}
A1,2
B1,3
C2,3
D 4
Show Explanation
String s2=new String("abc");---------->In this declaration, 2 objects will be created-one in the Heap area, and the other in the String constant pool, and s2 will always be pointing to the Heap area. But, already an object is created having the same content "abc". So, the existing object will be re-used.
Heap String constant pool
s2----------->"abc" "abc"<---------------s1
Now, the == operator is meant for always for reference comparison, i.e., it will result True if the string objects are same else False. On the other hand, equals() method defined in the String class is meant for content comparison, i.e, it will result True if the contents are same else False.
Here, (s1==s2) will result in False, as s1 is referring to the object in String constant pool, while s2 is referring to the object in the Heap, so the else part gets executed.
On the other hand, "s1.equals(s2)" will result in True because their contents are same, so the if part gets executed.
Hence, the output is-
2
3
Asked In ::
String s1="abc";----------------> In this declaration, only one String object will be created in the String constant pool, and s1 will be pointing to that object.
String s2=new String("abc");---------->In this declaration, 2 objects will be created-one in the Heap area, and the other in the String constant pool, and s2 will always be pointing to the Heap area. But, already an object is created having the same content "abc". So, the existing object will be re-used.
Heap String constant pool
s2----------->"abc" "abc"<---------------s1
Now, the == operator is meant for always for reference comparison, i.e., it will result True if the string objects are same else False. On the other hand, equals() method defined in the String class is meant for content comparison, i.e, it will result True if the contents are same else False.
Here, (s1==s2) will result in False, as s1 is referring to the object in String constant pool, while s2 is referring to the object in the Heap, so the else part gets executed.
On the other hand, "s1.equals(s2)" will result in True because their contents are same, so the if part gets executed.
Hence, the output is-
2
3
Read Full Answer
Report Error
Please Login First Click Here