Wednesday, August 25, 2010

NullPointerException: Adder.java

Courtesy of Sun Web Learning Center


Given:

1. class Adder {
2.   static Short s1,s2;
3.   public static void main(String [] args) {
4.     int x;
5.     s1 = 4;
6.     x = s1 + s2;
7.     System.out.print(x);
8.   }
9. }

What is the result?


A 4
B Compilation fails.
C A java.lang.ClassCastException is thrown.
D A java.lang.NullPointerException is thrown.
E A java.lang.IllegalStateException is thrown.

D is correct. s2 is a reference to a wrapper that is never initialized. If s2 had been initialized, the autoboxing would be correct.

No comments:

Post a Comment