Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | Java | Q4018 [ previous next ]

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

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?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.