Question discussion

Consider the following Java code snippet:Which of the following statements is/are true regarding the code given below?1. The Animal class s…

358827Medium DSSSB TGT Computer Science 0 replies 0 views
0
Consider the following Java code snippet:
Which of the following statements is/are true regarding the code given below?
1. The Animal class supports both default and parameterized constructors.
2. If line 1 in the comment is uncommented, the code will compile and run successfully.
3. If line 2 is executed, a2.displayInfo() will print "Animal: null, Age: 5".
4. If line 3 is executed, the program will throw a NullPointerException at runtime.
class Animal {
    String name;
    int age;
    Animal() {
        this.name = "Unknown";
        this.age = 0;
    }
    Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    void displayInfo() {
        System.out.println("Animal: " + name + ", Age: " + age);
    }
}
public class Main {
    public static void main(String[] args) {
        Animal a1 = new Animal();
        Animal a2 = new Animal("Dog", 5);
        a1.displayInfo();
        a2.displayInfo();
        // Error-prone code:
        //1. Animal a3 = new Animal("Cat");
        //2. a2.name = null; a2.displayInfo();
        // 3. Animal a4 = null; a4.displayInfo();
    }
}
  • A1 and 4 only
  • B2 only
  • C1,2 and 4 only
  • D1,3 and 4 only
Correct answer: D

Explanation

1 is true (both constructors exist). 2 is false, because Animal("Cat") has no matching constructor and gives a compile error. 3 is true, as a2.name = null prints "Animal: null, Age: 5". 4 is true, since calling a method on a null reference throws NullPointerException. So 1, 3 and 4 only are true.

Discussion 0

Nobody has replied yet. Start the discussion!