Given:
What is the result?
A. null
Richard
Donald
B. Richard Donald
C. Compilation fails.
D. An ArrayIndexOutOfBoundsException is thrown at runtime.
E. A NullPointerException is thrown at runtime.
Given:
What is the result?
A. null
Richard
Donald
B. Richard Donald
C. Compilation fails.
D. An ArrayIndexOutOfBoundsException is thrown at runtime.
E. A NullPointerException is thrown at runtime.
E
E
Exception in thread “main” java.lang.NullPointerException: Cannot read field “name” because “s” is null
at com.anand.scjp1.Question9.main(Question9.java:17)
it does null.name which is a complete NO NO. null pointer verified
E:
# javac Test15.java
# java Test15
Exception in thread “main” java.lang.NullPointerException
at Test15.main(Test15.java:14)
Answer E:
We will get the NullPointerException at runtime. The for loop will access all the elements of the “student” array. We have initialized the student[1] and student[2], but not student[0]. So it gets the default value, which is “null”. Now, at the println() method, we are trying to access instance-specific field (i.e. name) of an object that has not been initialized. Accordingly, in the first iteration, the value of “s” is student[0]. And since student[0] is null, then how can we access its field “name”?
Therefore, the NullPointerException kicks off.
It may print “null” though if we replace the println(s.name) by println(s). But it will print the object hashcode for the other student elements.
thats right, assigned : students[0] = new Student (“Bob”);
# javac Test15.java
# java Test15
Bob
Richard
Donald
E
A
E