DelphiFAQ Home Search:

java.lang.NullPointerException when using arrays?

 

comments5 comments. Current rating: 3 stars (3 votes). Leave comments and/ or rate it.

Question:

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

Answer:

Two possible explanations:
  1. You've indexed past the array bounds
  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);
          }
       }

Comments:

2007-06-15, 03:45:05
anonymous from Canada  
I have been trying to find a straight answer to this question for 3 hours, thank you so much.
2007-12-02, 06:54:43
anonymous from Colombia  
rating
It works for me!!!
2008-02-23, 16:41:37
anonymous from Finland  
rating
At last, simply elegant explanation.
2008-04-03, 00:19:35
anonymous from India  
rating
2008-05-02, 07:46:57
anonymous  
Thank u so much.. I'm trying to find this for hours... Thanks a lot again

 

 

Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option.
 
It seems that you are
from Washington, US .

Info/ Feedback on this

Show city and country
Show country only
Hide my location
Leave your comment here:
Please type in the code:
photo Add a picture:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity. The owner of this web site reserves the right to delete such material.