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.
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