JAVA Programming :: Basic Concepts - Discussion
25 / 64
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = "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 = "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,3
B1,4
C3,4
D2,4
Show Explanation
Here, the content of s1 and s2 is "abc", so in the String constant pool, a single object is created having the content as "abc", and s1 and s2 both will refer to the same object created. Since, both are referring to the same string object, hence (s1==s2) becomes True, and if part will execute.
On the other hand, the content for both s1 and s2 are the same, hence "s1.equals(s2)" also becomes True, so again the if part gets executed.
Therefore, the output will be-
1
3
Asked In ::
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, the content of s1 and s2 is "abc", so in the String constant pool, a single object is created having the content as "abc", and s1 and s2 both will refer to the same object created. Since, both are referring to the same string object, hence (s1==s2) becomes True, and if part will execute.
On the other hand, the content for both s1 and s2 are the same, hence "s1.equals(s2)" also becomes True, so again the if part gets executed.
Therefore, the output will be-
1
3
Read Full Answer
Report Error
Please Login First Click Here