0

This is my main codes:

Scanner input= new Scanner(System.in);

Student[] starray=new Student[5];

for (int i=0; i<3; i++)
{
    System.out.println("enter:");
    starray[i].name=input.next();   
    System.out.println("enter:");
    starray[i].family=input.next(); 
    System.out.println("enter:");
    starray[i].sid=input.nextInt();
}      
for(int i=0; i<3; i++)
        System.out.println(starray[i].name);

and i have one class :

String name,family;
Integer sid;

Student(){
       name="kh";
       family="kh";
       sid=0;}

when i run it have Exception below: Exception in thread "main" java.lang.NullPointerException at testcodes.TestCodes.main(TestCodes.java:19) Java Result: 1

3
  • Do you have an actual question? Commented Dec 5, 2014 at 16:58
  • You are not creating any students in the array.... All i see is you are making the array but not creating a new Student() @Chrismas007 I think his question is in the title.... Commented Dec 5, 2014 at 17:00
  • @3kings Saw this in Triage so I wasn't able to do an edit. Commented Dec 5, 2014 at 17:03

2 Answers 2

5

Student[] starray = new Student[5]; creates just the container. Every element within that container will be null.

You need to create each one in turn. Within your loop, consider

starray[i] = new Student();

Better still, build a strongly typed constructor to a Student, taking the name etc. as parameters. This will help to increase program stability.

Sign up to request clarification or add additional context in comments.

Comments

0

Java in this case is very similar to C++. In C++ when you declare an array of objects, all them still have not been initialized (these is no real objects within it), in other words the array is only a place holder for objects.

So your statement

Student[] starray = new Student[5];

in the form of visually could be

starray --> +------+------+------+------+------+
            | null | null | null | null | null |
            +------+------+------+------+------+

And after this statement

starray[0] = new Student();

would be

starray --> +------+------+------+------+------+
            |      | null | null | null | null |
            +---|--+------+------+------+------+
                |
                v
            +------------------+
            | Student Instance |
            +------------------+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.