Results 1 to 4 of 4
  1. #1
    anoorally is offline Member
    Join Date
    Jan 2012
    Posts
    28
    Rep Power
    0

    Default NullPointerException when there is data in array

    I have an array which has 6 items in it. When I print the array size, it displays 6. But when I try to access the item at index 1, it gives me the NullPointerException error:
    Java Code:
    Tile[] tiles = (Tile[])input;
    print("tile array length: "+ tiles.length);
    print("tile-->"+tiles[0].getTileNum());
    print("tile-->"+tiles[1].getTileNum());
    Here is the output:
    tile array length: 6
    tile-->45
    java.lang.NullPointerException


    It traces back to the line:
    Java Code:
    print("tile-->"+tiles[1].getTileNum());
    Any idea whats going wrong?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: NullPointerException when there is data in array

    The length of an array just returns how many items the array can hold, nothing more. It tells you nothing about whether the elements in the array are filled or not. Think of it as if it were a parking lot. The length tells you how many parking spots are present in the lot, but tells you nothing about how many have cars parked in them yet.

    Your problem is that you're trying to call a method on a null variable -- on an array element that does not yet refer to an object.

  3. #3
    anoorally is offline Member
    Join Date
    Jan 2012
    Posts
    28
    Rep Power
    0

    Default Re: NullPointerException when there is data in array

    Thank you, i got to my error :)

  4. #4
    tnrh1 is offline Senior Member
    Join Date
    Aug 2011
    Posts
    251
    Rep Power
    3

    Default Re: NullPointerException when there is data in array

    According to furable post, the default value on an object is a null so you have to initialize the array elemnts if you want to have an objects in it.
    Something like ar[k] = new Tile(), but to every element of the array.

Similar Threads

  1. NullPointerException when accessing array
    By aianta in forum New To Java
    Replies: 3
    Last Post: 10-15-2011, 10:19 PM
  2. Data structures(sort) nullpointerexception
    By Fabken in forum New To Java
    Replies: 6
    Last Post: 07-28-2011, 09:01 PM
  3. text into array...nullpointerexception
    By csuever in forum New To Java
    Replies: 4
    Last Post: 04-01-2011, 12:08 AM
  4. Replies: 8
    Last Post: 03-31-2011, 06:09 AM
  5. Add data to an array
    By adlb1300 in forum New To Java
    Replies: 8
    Last Post: 11-05-2007, 02:01 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •