java空指標出現的情況:拆箱裝箱

liang302發表於2024-09-08

讓普通變數 long = 一個空的Long物件

public class UnboxingNpe {

    private static int add(int x, int y) {
        return x + y;
    }

    private static boolean compare(long x, long y) {
        return x >= y;
    }

    public static void main(String[] args) {

        // 1. 變數賦值自動拆箱出現的空指標
        // javac UnboxingNpe.java
        // javap -c UnboxingNpe.class
        Long count = null;
        long count_ = count;

        // 2. 方法傳參時自動拆箱引發的空指標
//        Integer left = null;
//        Integer right = null;
//        System.out.println(add(left, right));

        // 3. 用於大小比較的場景
//        Long left = 10L;
//        Long right = null;
//        System.out.println(compare(left, right));
    }
}

相關文章