Java OCA OCP Practice Question 2757

Question

Consider the following program:

public class Main {
        public static void main(String []args) {
               String s1 = "hi";
               String s2 = new String("hi");
               String s3 = "hi";

               if(s1 == s2) {
                       System.out.println("s1 and s2 equal");
               } else {
                       System.out.println("s1 and s2 not equal");
               }//from w  w  w  . j  ava  2s.  c  om

               if(s1 == s3) {
                       System.out.println("s1 and s3 equal");
               } else {
                       System.out.println("s1 and s3 not equal");
               }
        }
}

Which one of the following options provides the output of this program when executed?

a)
s1 and s2 equal/* w w w.  ja v a2 s .  c o m*/
s1 and s3 equal
b)
s1 and s2 equal
s1 and s3 not equal
c)
s1 and s2 not equal
s1 and s3 equal
d)
s1 and s2 not equal
s1 and s3 not equal


c)

Note

JVM sets a constant pool in which it stores all the string constants used in the type.

If two references are declared with a constant, then both refer to the same constant object.

The == operator checks the similarity of objects itself (and not the values in it).

Here, the first comparison is between two distinct objects, so we get s1 and s2 not equal.

On the other hand, since references of s1 and s3 refer to the same object, we get s1 and s3 equal.




PreviousNext

Related