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 null pointer exception by Integer 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 "null pointer exception by Integer" Watch "null pointer exception by Integer" New topic

null pointer exception by Integer

Tuna Töre
Ranch Hand

Joined: Aug 17, 2008
Posts: 220

I took this code from SUN's assessment exam and modified it a little

return Integer.getInteger(arg); I want to ask why this line gives null pointer exception ?


Core Spring Certified Professional + SCJP 6.0 + SCWCD 1.5
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

Do you know what the method Integer.getInteger() does? It most likely does not do what you think it does.

The API documentation says:
Determines the integer value of the system property with the specified name.

If there is no system property named "42", then Integer.getInteger() returns null, and because Parser.getInt() returns a primitive int, the JVM is trying to auto-unwrap null to an int - which causes a NullPointerException.

It's a trick question...

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Harvinder Thakur
Ranch Hand

Joined: Jun 10, 2008
Posts: 231
If you check the use of getInteger() method then you would get an answer to your question.
Looking at the code it seems you are better off using valueOf() or parseInt() method of Integer class.

Tuna Töre
Ranch Hand

Joined: Aug 17, 2008
Posts: 220


very tricky, actually question is not like that I have modified it and see the null pointer exceltion, thanks I got it

The real question is like above and works fine
I agree. Here's the link:
subject: null pointer exception by Integer
It's not a secret anymore!