What will be the output of the following program?

class Person {
    public String name;
    public int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public boolean equals(Object obj) {
       return obj instanceof Person
               && this.age == ((Person)obj).age
               && this.name.equals(((Person)obj).name);
   }
}

public class Quizful {
    public static void main(String[] args){
        Person p1 = new Person(null, 10);
        Person p2 = new Person("Alex", 22);
        System.out.println(p1.equals(p2));
    }
}
Explanation
&& is a short circuit operator in Java, which means that once it evaluates the left expression as false - it no longer evaluates the right expression.
In our case, in the equals method evaluates

obj instanceof Person 
to true;

this.age == ((Person)obj).age 
to false; the next expression,

this.name.equals(((Person)obj).name);
is not evaluated at all, and the method returns false.
Changing the && operator to || or & would result in a java.lang.NullPointerException

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes