This class compiles just fine:
public class Student{
//define variables
static String name;
//define constructor
public Student(String n){
name = n;
}
//define method to display name
public static void displayStudent(){
System.out.println("Name: " + name);
}
}
Here is the class where I am trying to call the displayStudent()
method, but I am getting java.lang.NullPointerException exception coming from the for loop
:
public class MyClass{
//define array of object Student
private Student[] students;
//constructor
MyClass(int size){
Student[] students = new Student[size];
}
//define method to display the students variable
public void displayAllStudents(){
for (int i = 0; i <= students.length; i++){
students[i].displayStudent();
}
}
I am trying to fixing it with Eclipse, but it says that in MyClass "the value of the local variable students
is not used". Where is my mistake?