NullPointerException when comparing int with Integer

Have you meet this situation: compare Integer with its primitive type int? The situation seems like the following example.

public class NullPointerExceptionCaseStudy {

    public static void main(String[] args) {
        Integer startNum = new Integer(10);
        Countdown counter = new Countdown(startNum);
        //what if startNum is assigned to null?
        //***the statement 0==counter.getCount() will throw an NullPointerExcepion***
        if (0 == counter.getCount()) {
            System.out.printnln("Time's up");
        }
    }

    class Countdown{
        private Integer count;

        public Countdown(Integer count) {
            this.count = count;
        }
        public Integer getCount() {
            return count;
        }
    }
}

Why the conditional statement throws an Exception when startNum is assigned to null?

According to the Java Specification (chapter 5. Conversions),

At run time, unboxing conversion proceeds as follows:
If r is a reference of type Boolean, then unboxing conversion converts r into r.booleanValue()
If r is a reference of type Byte, then unboxing conversion converts r into r.byteValue()
If r is a reference of type Character, then unboxing conversion converts r into r.charValue()
If r is a reference of type Short, then unboxing conversion converts r into r.shortValue()
If r is a reference of type Integer, then unboxing conversion converts r into r.intValue()
If r is a reference of type Long, then unboxing conversion converts r into r.longValue()
If r is a reference of type Float, unboxing conversion converts r into r.floatValue()
If r is a reference of type Double, then unboxing conversion converts r into r.doubleValue()
If r is null, unboxing conversion throws a NullPointerException

The conditional statement “if (0 == counter.getCount())” splits several steps:
1. Integer temp = counter.getCount()
2. int intTemp = temp.intValue() // If temp is null, NullPointerException is thrown
3. compare 0 with intTemp

Solution - Revise the conditional statement as below:

//Objects is introduced since 1.7 in java.util package
/*
public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }
*/
if (Objects.equals(counter.getCount(), 0) {
    //your implementation
}

The same with multiplicative operators(*, /, %) and additive operators(+,-), the operands must be a type that is convertible to a primitive numeric type.

猜你喜欢

转载自blog.csdn.net/zhangmagle125/article/details/51517235