-3

i am beginner in java programing so i dont khow about the null pointer exception please any body help me how can i solve this type of error -i have two class one with name Student.java and another with SrDemo.java -i write gatter satter in Student class and use this is SrDemo class But when i call the method using array its generate null pointer exception how can i solve this and i have solution this with my commented text but i want this solution with using array so please if anybody know tell me thanks in advance.. this below is my my code for both classes

  SrDemo.java 
...........
public class SrDemo {
    public static void main(String args[]){
        Student sd[]=new Student[2];
        sd[0].setName("name");
        System.out.println(sd[0].getName());
        /*Student sd;
        for(int i=0;i<5;i++) {
            sd = new Student();
            sd.setName("jagdish " + i);
            sd.setCity("Baroda " + i);
            System.out.println(sd.getName());
            System.out.println(sd.getCity());
        }*/
    }
}

Student.java
...........

public class Student {
    private String name;
    private String city;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
}


error
.......
Exception in thread "main" java.lang.NullPointerException
    at Serialize.SrDemo.main(SrDemo.java:8)
Jagdish
  • 129
  • 1
  • 8

1 Answers1

1

You create an array which takes Students as its input but you never estuary put one in there. So the students[0].setName("name") never actually sets the name property of an object. The consequence is, you can't access it either.

You already pointed out the solution: iteratively filling your array with students although you just print the student's attributes in your for loop so far. Using something like students[i] = new Student() would give you an array with empty students which you can also fill after you created each one.

Niklas
  • 375
  • 1
  • 3
  • 17