Reputation: 83
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("-------------------");
}
}
Upvotes: 0
Views: 186
Reputation: 178293
You are not assigning a new Student
to the array in this for
loop.
for (Student s : sdb) {
s = takeInput();
}
The takeInput
method is returning a Student
properly, but you've assigned it to a local reference s
, not as an element in the array sdb
. The elements of the array remain null
, and the NullPointerException
comes from attempting to call printStudentDetails
on null
in the selectAllStudent
method.
You can convert the enhanced for
loop to a standard for
loop, assigning the Student
with an array access expression.
for (int i = 0; i < sdb.length; i++)
{
sdb[i] = takeInput();
}
Upvotes: 3