-1

I have checked almost all kinds of declarations for an array of objects. Please suggest the required changes.This code gives me a null pointer exception as follows:

Exception in thread "main" java.lang.NullPointerException at objarray.main(objarray.java:33)

import java.util.*;
class Prod {
    private int    pno, pcost;
    private String pname;

    void accept() {
        Scanner sc = new Scanner( System.in );
        System.out.println( "Enter pno" );
        pno = sc.nextInt();
        System.out.println( "Enter pname" );
        pname = sc.next();
        System.out.println( "Enter pcost" );
        pcost = sc.nextInt();
    }

    void print() {
        System.out.println( pno + "\t" + pname + "\t" + pcost );
    }
}

class objarray {
    public static void main( String[] args ) {
        int i;
        Prod[] p = new Prod[3];
        for( i = 0; i < 3; i++ )
            p[i].accept();
        for( i = 0; i < 3; i++ )
            p[i].print();
    }
}
3
  • Initialize array Elements(Objects) p[i]=new Prod(); Commented Jul 14, 2014 at 8:08
  • 1
    well u need to create every time new object into the for loop. see. Commented Jul 14, 2014 at 8:10
  • +1 because u are at learning stage. :) Commented Jul 14, 2014 at 8:12

3 Answers 3

7

You need to initialize the elements of your array:

Prod[] p = new Prod[3];
for(i = 0;i<3;i++)
    p[i] = new Prod(); // added this line
    // rest of code

The statement Prod[] p = new Prod[3]; just allocates space for the references to Prod objects - it doesn't create them.

1
  • Thanks a lot! That was of great help! Commented Jul 14, 2014 at 8:25
0
    Prod[] p = new Prod[3];
    for(i = 0;i<3;i++){
        p[i] = new Prod(); // this will assign in each
// rest your logic.

    }

hope that helps.

1
  • Thanks a lot! That was of great help! Commented Jul 14, 2014 at 8:24
0

Initialise the elements in the array to avoid null pointer exception to get a clear picture try eclipse debugger where you will know the place where there are null values and you can deal these issues in a easy manner

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.