Spring Hibernate Core Java coding questions frequently asked in written tests and interviews - part 2: equals Vs ==



Core Java coding questions frequently asked in job interviews - part 1 


Q2. What will be the output of the following code snippet?

   Object s1 = new String("Hello");
Object s2 = new String("Hello");

if(s1 == s2) {
System.out.println("s1 and s2 are ==");
}else if (s1.equals(s2)) {
System.out.println("s1 and s2 are equals()");
}

A2. The answer is:


 s1 and s2 are equals()



Here is the explanation with a diagram.






So, the above question tests your understanding of "==" versus "equals( )" applied to objects in Java. One compares the references and the other compares the actual values.


Here are some follow on questions:


Q. What will be the output for the following code snippet?

 Object s1 = "Hello";
Object s2 = "Hello";

if (s1 == s2) {
System.out.println("s1 and s2 are ==");
} else if (s1.equals(s2)) {
System.out.println("s1 and s2 are equals()");
}

A. The answer is

s1 and s2 are ==

Now the above answer violates the rule we saw before. This is a special case (or rule) with the String objects and a typical example of the flyweight design pattern in action. This design pattern is used to conserve memory by reducing the number of objects created. The String object creates a pool of string and reuse an existing String object from the pool if the values are same instead of creating a new object. The flyweight pattern is all about object reuse. This rule applies only when you declare the String object as Object s = "Hello"; without using the keyword "new".





This is a very popular Java  interview question.

More Java coding questions and answers