[Updated] Goldman Sachs Aptitude Test Questions and Answers
Practice List of TCS Digital Coding Questions !!!
Take 50+ FREE!! Online Data Interpretation Mock test to crack any Exams.

JAVA Programming :: Basic Concepts - Discussion

Home > JAVA Programming > Basic Concepts > MCQs Questions Discussion

25 / 64

What all gets printed when the following gets compiled and run.

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

Answer: Option (Login/Signup)

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 ::

Post Your Answer Here:     

Reply    
Rate This: +0 -0
    Report


Report Error

Please Login First Click Here