int类型在接收null会报错,需要使用Java包装类型Integer,且Integer不能equal String字符串

发布时间 2023-06-05 22:23:31作者: oktokeep
int类型在接收null会报错,需要使用Java包装类型Integer,且Integer不能equal String字符串
package com.example.core.mydemo.json2;

/**
 * int类型在接收null会报错,需要使用Java包装类型Integer
 */
public class IntegerNullTest {
    public static void main(String[] args) {
        Integer aaa = null;
        //output: total=100
        System.out.println("total=" + calc(aaa));

        //Exception in thread "main" java.lang.NullPointerException
        //    at com.example.core.mydemo.json2.IntegerNullTest.main(IntegerNullTest.java:10)
//        System.out.println("total2=" + calc2(aaa));

        //unsame  字符串与Integer比较,JAVA规范错误写法
        Integer bbb = 100;
        if("100".equals(bbb)){
            System.out.println("same");
        }else{
            System.out.println("unsame");
        }

    }

    private static Integer calc(Integer aaa) {
        return 100;
    }

    /**
     * int类型在接收null会报错
     * @param aaa
     * @return
     */
    private static Integer calc2(int aaa) {
        return 100;
    }

}