Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static problem...

 
Prashanth Lingala
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Pizza{
}

public class ArrayReferences
{
static int a[];
static Pizza[] smallPizzas;
public static void main(String[] args)
{

System.out.print(a[0] + " "+ " " +smallPizzas[0]);

}
}

/*
Exception in thread main
java.lang.NullPointerException
at ArrayReferences.main(ArrayReferences.java:11)

Press any key to continue...

*/

why am i getting this output:???
where have i erred???
 
K Riaz
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are trying to access two empty arrays, hence the NullPointerException. What were you expecting? if you want to initialise both of them, use a for loop:



[ February 08, 2005: Message edited by: Kashif Riaz ]
[ February 08, 2005: Message edited by: Kashif Riaz ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kashif is correct.

I would just remind you that array length must be set at the time of instantiation. For example...

The array's elements can be automatically initialized (null for object references, or zero for primitive values), but you need to instantiate the array first -- otherwise the array reference itself will be automatically initialized to null, and trying to access a particular element will result in the null pointer exception you're seeing now.
[ February 08, 2005: Message edited by: marc weber ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note: This problem has nothing to do with the array references being static.

As static declarations, they will automatically initialize at class load time. If they were non-static, they would automatically initialize upon instantiation. But in both cases, the array references will initialize to null, and you'll get an exception when you try to access an element.
[ February 08, 2005: Message edited by: marc weber ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic