File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes NullPointerException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "NullPointerException" Watch "NullPointerException" New topic


Sujatha Musunuri

Joined: Oct 23, 2007
Posts: 16
1. public class Boxer1 {
2. Integer i;
3. int x;
4. public Boxer1(int y) {
5. x=i+y;
6. System.out.println(x);
7. }
8. public static void main(String[] args) {
9. new Boxer1(new Integer(4));
10. }
11. }

The Ans for this is 'NullPointerException' at runtime. Can some one let me know why is it giving that Exception?
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

Since you didn't initialize the Integer i, by default i will be null. Hence, you get the NullPointerException when trying to perform the addition.

SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Bert Bates

Joined: Oct 14, 2002
Posts: 8898
Hi there Musu Musu,

Please help us out with two things:

1 - is that your real name? If not, please change your display name to be your first and last name. That's the policy at the ranch and it keeps things friendlier.

2 - it's great to post mock questions to discuss, but please indicate where you got the question when you post it - it's kind to the autor of the qeustion, and it can help us help you.



Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Hi Musu,
Auto-unboxing a null reference will always cause a NullPointerException.

SCJP 5.0
I agree. Here's the link:
subject: NullPointerException
It's not a secret anymore!