1
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?

ethelake
  • 57
  • 6

3 Answers3

3

You created an array of size two that is designated to hold Student objects with Student studentArray[] = new Student[2];, so now you have an empty container. Then you tried to access an element of that empty container which threw the null pointer exception. You need to put Student objects into your Student container to access the containers elements.

billie
  • 152
  • 13
0

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);
    }
}
mba12
  • 2,364
  • 5
  • 25
  • 49
0
public class HelloWorld{

public static void main(String []args){

        Student studentArray[] = new Student[2];
        HelloWorld helloWorld = new HelloWorld();

        for(int i=0; i<studentArray.length; i++) {
            studentArray[i] = helloWorld.new Student();
        }

        studentArray[0].marks = 100;
        studentArray[1].marks = 75;

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

        System.out.println(m);
    }

class Student {
    int marks;
}

}

You are getting a NullPointerException because you haven't initialised Student objects within the studentArray. You then try to access something that doesn't exist hence the error.

The above code should fix your error.

Brunaldo
  • 324
  • 3
  • 10