cohort cohort - 1 month ago 11
Java Question

Is this right way to initialize an array of objects?

public class HelloWorld{


class Student {
int marks;

}


public static void main(String []args){

Student studentArray[] = new Student[2];
studentArray[0].marks = 100;
studentArray[1].marks = 75;

int m=0;
m = studentArray[0].marks;

System.out.println(m);


}
}


This compiles with no problem but when I execute it, I am getting null pointer exception error as following:


Exception in thread "main" .lang.NullPointerException at
HelloWorld.main(HelloWorld.java:13)


can somebody help me to locate where the cause is?

Answer

Something like this is what you are looking for:

public class HelloWorld{


class Student {
    int marks;
}


public static void main(String []args){

        Student studentArray[] = new Student[2];
        studentArray[0] = new Student(); // .marks = 100;
        studentArray[1] = new Student(); // .marks = 75;
        studentArray[0].marks = 100;
        studentArray[1].marks = 75;

        int m=0;
        m = studentArray[0].marks;

        System.out.println(m);
    }
}