Java - "java.lang.NullPointerException" when using arrays

Adopt from

http://www.delphifaq.com/faq/f618.shtml


Question:

"java.lang.NullPointerException" when using arrays

Explanation:

Two possible explanations:

1.You've indexed past the array bounds

public class Test {

    public int[] i = new int[8];

    public static void main(String args[]){

        int j;

        for (j=0;j<8;j++){

            i[j]=j;

        }

        System.out.println(i[7]+"");

        System.out.println(i[8]+""); //Out of range

    }

}

2.You haven't initialized the array correctly

   // example of an incorrectly initialized array:

       public class Test {
          public static void main(String args[]) {
             String sa[] = new String[5];
             sa[0].charAt(0);
          }
       }

    // example of a correctly initialized array:

       public class Test {
          public static void main(String args[]) {
             String sa[] = new String[5];

             for(int i = 0; i < 5; i++) {
                sa[i] = new String();
             }
 
             sa[0].charAt(0);
          }
       }
本篇發表於 Java 並標籤為 , , 。將永久鏈結加入書籤。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *