Consider the following Java code snippet: class Animal {
Consider the following Java code snippet:
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();
}
}
Which of the following statements is/are true regarding the above code?
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.
Show answerHide answer
Correct answer: (D) 1,3 and 4 only
Explanation
1 is true (no-arg and two-arg constructors). 2 is false: there is no Animal(String) constructor, so it would not compile. 3 is true: concatenating null prints "null". 4 is true: calling a method on a null reference throws NullPointerException.