0

Following is what I have done so far, but I get an exception every time I run it:

class Student{
    int sNo;
}

public class Array {
    public static Student[] createObj() {
        Student[] s = new Student[10];
        for(int i = 0; i<10;i++) {
            s[i].sNo = i+1;
        }
        return s;
    }
    public static void main(String[] args) {
        Student student[] = createObj();
        for(int i = 0; i<10;i++) {
            System.out.print(student[i].sNo);
        }
    }
}

This is the exception:

Exception in thread "main" java.lang.NullPointerException
    at Array.createObj(Array.java:9)
    at Array.main(Array.java:14)
  • You instantiate only the array, you have also to instante the Student object to each position. s[i] = new Student() – Lungu Daniel Jul 11 '20 at 21:39
  • When you create array it is filled with default values, which for reference types like classes is `null`. In other words `new Student[10]` is same as `new Student[]{null,null, ... , null}`. With `s[i].sNo = i+1;` you are ending up with `null.sNo = i+1;`. Fill array with Student objects first, then you can access them with `s[i]`. – Pshemo Jul 11 '20 at 21:41

0 Answers0