Java Array 常見報錯npe (NullPointerException )、ArrayIndexOutOfBoundsException


 

本文介紹array報錯,

  數組索引越界異常: ArrayIndexOutOfBoundsException,

  空指針 npe :NullPointerException 

package myArray;
/*
 * 兩個常見小問題:
 *         ArrayIndexOutOfBoundsException:數組索引越界異常
 *             產生的原因:我們訪問了不存在的索引
 *
 *         NullPointerException:空指針異常
 *             產生的原因:數組已經不在指向堆內存的數據了,你還使用數組名去訪問元素
 */
public class ArraychangjianExecption {
    public static void main(String[] args) {
        int[] arr = {1,2,3};
        System.out.println(arr[3]);
    }
}

結果如下

 

 

public class ArraychangjianExecption {
    public static void main(String[] args) {
        int[] arr = {1,2,3};
        arr = null;
//        System.out.println(arr);
        System.out.println(arr[1]);
    }
}

結果如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM