Java Daily, Quiz 2

Welcome to Java daily quiz 2, test yourself with this Java quiz. The answer and explanation are given at the end for your reference.
Check out all the Java daily quiz questions at https://www.javaguides.net/p/java-daily-quiz.html

Java Daily, Quiz 2 - Consider the following program:

public class StrEqual {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = new String("hello");
        String s3 = "hello";
        if (s1 == s2) {
            System.out.println("s1 and s2 equal");
        } else {
            System.out.println("s1 and s2 not equal");
        }
        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
      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


a)
s1 and s2 equal
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

Answer

c)
s1 and s2 not equal
s1 and s3 equal
Explanation: 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 to s1 and s3 refer to the same object, we get s1 and s3 equal.
Note: We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
Check out all the Java daily quiz questions at https://www.javaguides.net/p/java-daily-quiz.html.

Comments