NullPointerException when comparing int with Integer

本文探讨了在Java中比较Integer对象与其基本类型int时可能遇到的空指针异常问题。通过具体示例展示了当Integer对象为null时,如何正确进行比较以避免异常的发生,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值