NullPointerException

Hi!

I have this simple piece of code and it s agiving a NullPointerException for no reason!

publicclass Main{

public Main(){

allStudents =new Stu[1];

allStudents[0].Name1 ="re";//Null Pointer Exception occurs here

}

Stu[] allStudents;

publicstaticvoid main(String[] args){

new Main();

}

class Stu

{

String Name1;

String Address1;

String Nationality1;

String DOB1;

String Sex1;

int TelephoneNo;

int ID_nos;

int MobileNo;

int MarksEnglish;

int MarksMaths;

int MarksComputers;

}

}

[1402 byte] By [prakharbirlaa] at [2007-11-26 20:41:58]
# 1

allStudents is an array of references, not an array of objects. Upon creation of the array, all it's elements are null. They're references that don't point to any objects. You need to do allStudents[0] = new Stu();

or whatever the appropriate constructor is, or assign a reference to an existing object to it.

jverda at 2007-7-10 2:01:02 > top of Java-index,Java Essentials,Java Programming...
# 2

Time to go fruit picking again.

I want to pick some apples, so I make a crate that can hold 100 apples.

After the crate is finished how many apples does it hold? None. I now

have to go and pick the apples and put them in the crate.

The same applies here. Your array is the crate and after you have made

it, there are no Objects in it. You have to create the Objects first and place

them in the array.

floundera at 2007-7-10 2:01:02 > top of Java-index,Java Essentials,Java Programming...
# 3

public class Main

{

Stu[] allStudents;

public static void main(String[] args) {

new Main();

}

public Main() {

allStudents = new Stu[1];

allStudents[0] = new Stu();

allStudents[0].Name1 = "re";

}

class Stu

{

String Name1;

String Address1;

String Nationality1;

String DOB1;

String Sex1;

int TelephoneNo;

int ID_nos;

int MobileNo;

int MarksEnglish;

int MarksMaths;

int MarksComputers;

}

}

Im pretty sure the above code works. Im not sure whats wrong with your code (apart from the fact that it was abit 'messy'). I dont see why you would not consider using constructor methods tho. i.e. allStudents[0] = new Stu("Helen" ...);

Anyhow, if you are going to do it as i suggested above, you may need some sort of loop to go through each element of the array and initialise each of them as a Stu object.

hope this helps

jazza_guya at 2007-7-10 2:01:02 > top of Java-index,Java Essentials,Java Programming...
# 4
Thanks all for the help! And a special thanks for the apple story! Brightened my day (@) !!!
prakharbirlaa at 2007-7-10 2:01:02 > top of Java-index,Java Essentials,Java Programming...