The following code throws NullPointerException:
int num = Integer.getInteger("123");
Is my compiler invoking getInteger on null since it’s static? That doesn’t make any sense!
What’s happening?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The Big Picture
There are two issues at play here:
Integer getInteger(String)doesn’t do what you think it doesnullin this caseIntegertointcauses auto-unboxingIntegerisnull,NullPointerExceptionis thrownTo parse
(String) "123"to(int) 123, you can use e.g.int Integer.parseInt(String).References
IntegerAPI referencesstatic int parseInt(String)static Integer getInteger(String)On
Integer.getIntegerHere’s what the documentation have to say about what this method does:
In other words, this method has nothing to do with parsing a
Stringto anint/Integervalue, but rather, it has to do withSystem.getPropertymethod.Admittedly this can be quite a surprise. It’s unfortunate that the library has surprises like this, but it does teach you a valuable lesson: always look up the documentation to confirm what a method does.
Coincindentally, a variation of this problem was featured in Return of the Puzzlers: Schlock and Awe (TS-5186), Josh Bloch and Neal Gafter’s 2009 JavaOne Technical Session presentation. Here’s the concluding slide:
For completeness, there are also these methods that are analogous to
Integer.getInteger:Boolean.getBoolean(String)Long.getLong(String)Related questions
On autounboxing
The other issue, of course, is how the
NullPointerExceptiongets thrown. To focus on this issue, we can simplify the snippet as follows:Here’s a quote from Effective Java 2nd Edition, Item 49: Prefer primitive types to boxed primitives:
There are places where you have no choice but to use boxed primitives, e.g. generics, but otherwise you should seriously consider if a decision to use boxed primitives is justified.
Related questions