I am getting a null pointer exception in the selectAllStudent Method. When I am using foreach loop but When I am using a normal loop it is working fine. Please explain the reason. Thank you
Driver Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) {
Student[] sdb = new Student[2];
try {
for (Student s : sdb) {
s = takeInput();
}
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
selectAllStudent(sdb);
}
static void selectAllStudent(Student[] sdb) {
for (Student s : sdb) {
s.printStudentDetails(); // Getting NullPOinterException here
}
}
public static Student takeInput() throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the details ");
System.out.print("ROLL :"); int rollno = Integer.parseInt(in.readLine());
System.out.print("NAME :"); String name = in.readLine();
System.out.print("BRANCH :"); String branch = in.readLine();
return (new Student(rollno,name,branch));
}
}
Student Class
public class Student {
private int rollno;
private String name;
private String branch;
Student(int rollno, String name, String branch) {
this.rollno = rollno;
this.name = name;
this.branch = branch;
}
void printStudentDetails() {
System.out.println("ROLLNO :" + rollno);
System.out.println("NAME :" + name);
System.out.println("BRANCH :" + branch);
System.out.println("-------------------");
}
}