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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值