What is the result?

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.

Download Printable PDF. VALID exam to help you PASS.

11 thoughts on “What is the result?

  1. Exception in thread “main” java.lang.NullPointerException: Cannot read field “name” because “s” is null
    at com.anand.scjp1.Question9.main(Question9.java:17)

  2. E:
    # javac Test15.java
    # java Test15
    Exception in thread “main” java.lang.NullPointerException
    at Test15.main(Test15.java:14)

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

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

    2. thats right, assigned : students[0] = new Student (“Bob”);

      # javac Test15.java
      # java Test15
      Bob
      Richard
      Donald

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.