This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes static problem... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static problem..." Watch "static problem..." New topic
Author

static problem...

Prashanth Lingala
Ranch Hand

Joined: Nov 13, 2004
Posts: 66
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???


Have A Nice Day !!!
K Riaz
Ranch Hand

Joined: Jan 08, 2005
Posts: 375
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

Joined: Aug 31, 2004
Posts: 11343

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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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 ]
 
Don't get me started about those stupid light bulbs.
 
subject: static problem...
 
Similar Threads
need help with assignment
Array Initializer Doubt - Bert please explain..
array syntax new Pizza[1]
Why different output ???
doubt in parameter passing