Boolean.valueOf() produces NullPointerException sometimes

后端 未结 5 1556
名媛妹妹
名媛妹妹 2021-01-30 08:14

I have this code:

package tests;

import java.util.Hashtable;

public class Tests {

    public static void main(String[] args) {

        Hashtable

        
5条回答
  •  忘了有多久
    2021-01-30 08:23

    As Andy already very well described the reason of NullPointerException:

    which is due to Boolean un-boxing:

    Boolean.valueOf(modifiedItems.get("item1"))
    

    get converted into:

    Boolean.valueOf(modifiedItems.get("item1").booleanValue())
    

    at runtime and then it throw NullPointerException if modifiedItems.get("item1") is null.

    Now I would like to add one more point here that un-boxing of the following classes to their respective primitives can also produce NullPointerException exception if their corresponding returned objects are null.

    1. byte - Byte
    2. char - Character
    3. float - Float
    4. int - Integer
    5. long - Long
    6. short - Short
    7. double - Double

    Here is the code:

        Hashtable modifiedItems1 = new Hashtable();
        System.out.println(Boolean.valueOf(modifiedItems1.get("item1")));//Exception in thread "main" java.lang.NullPointerException
    
        Hashtable modifiedItems2 = new Hashtable();
        System.out.println(Byte.valueOf(modifiedItems2.get("item1")));//Exception in thread "main" java.lang.NullPointerException
    
        Hashtable modifiedItems3 = new Hashtable();
        System.out.println(Character.valueOf(modifiedItems3.get("item1")));//Exception in thread "main" java.lang.NullPointerException
    
        Hashtable modifiedItems4 = new Hashtable();
        System.out.println(Float.valueOf(modifiedItems4.get("item1")));//Exception in thread "main" java.lang.NullPointerException
    
        Hashtable modifiedItems5 = new Hashtable();
        System.out.println(Integer.valueOf(modifiedItems5.get("item1")));//Exception in thread "main" java.lang.NullPointerException
    
        Hashtable modifiedItems6 = new Hashtable();
        System.out.println(Long.valueOf(modifiedItems6.get("item1")));//Exception in thread "main" java.lang.NullPointerException
    
        Hashtable modifiedItems7 = new Hashtable();
        System.out.println(Short.valueOf(modifiedItems7.get("item1")));//Exception in thread "main" java.lang.NullPointerException
    
        Hashtable modifiedItems8 = new Hashtable();
        System.out.println(Double.valueOf(modifiedItems8.get("item1")));//Exception in thread "main" java.lang.NullPointerException
    

提交回复
热议问题