Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does this code throw a NullPointerException?

Eventually I got the answer, but it puzzled me for a while.

Why does the following code throws NullPointerException when run?

import java.util.*;

class WhyNullPointerException {
    public static void main( String [] args ){
       // Create a map
        Map<String,Integer> m = new HashMap<String,Integer>();
        // Get the previous value, obviously null.
        Integer a = m.get( "oscar" );
        // If a is null put 1, else increase a
        int p = a == null ? 
            m.put( "oscar", 1) : 
            m.put( "oscar", a++ ); // Stacktrace reports Npe in this line
    }
}
like image 960
OscarRyz Avatar asked Jul 02 '10 01:07

OscarRyz


People also ask

How do I fix NullPointerException?

NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

What does NullPointerException mean in Java?

NullPointerException s are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException .

Why am I getting null in Java?

The java. lang. NullPointerException is thrown in Java when you point to an object with a null value. Java programmers usually encounter this infamous pointer exception when they forget to initialize a variable (because null is the default value for uninitialized reference variables).


2 Answers

Because m.put returns null (which indicates that there's no "previous" value) while you're trying to assign it to int. Replace int p by Integer p and it will work.

This is specified in JLS 5.1.8:

5.1.8 Unboxing Conversion

At run time, unboxing conversion proceeds as follows:

  • If r is null, unboxing conversion throws a NullPointerException

Unrelated to the problem, just a side suggestion with DRY in mind, consider writing it so:

    Integer p = m.put("oscar", a == null ? 1 : a++);

It's a bit more readable :)

like image 184
BalusC Avatar answered Oct 31 '22 06:10

BalusC


You are assigning int p to the return value of m.put(). But put() returns null in this situation, and you can't assign an int to null.

From the Javadocs for HashMap.put():

Returns: previous value associated with specified key, or null if there was no mapping for key.

like image 40
Justin Ardini Avatar answered Oct 31 '22 05:10

Justin Ardini