Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q4018 Why do I keep getting a "java.lang.NullPointerException" when using arrays?

You are here: irt.org | FAQ | Java | Q4018 [ previous next ]

Two possiblities:

  1. You've indexed past the array bounds

  2. You haven't initialized the array correctly

See the following example

    // 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);
          }
       }

Of course now you'll get a "java/lang.StringIndexOutOfBoundsException" but that's because all of the Strings are empty ;-)

Feedback on 'Q4018 Why do I keep getting a "java.lang.NullPointerException" when using arrays?'

©2018 Martin Webb