-4

While I am executing the below code in eclipse:

class Account
{
  int a, b;
  public void setData(int c, int d)
  {
    a=c;
    b=d;
  }

  public void showData()
  {
    System.out.println("Value of a: "+a);
    System.out.println("Value of b: "+b);
  }
}

public class ObjectArray 
{
  public static void main(String args[])
  {
    Account obj[] = new Account[2];
    //obj[0]=new Account();
    //obj[1]=new Account();
    obj[0].setData(1, 2);
    obj[1].setData(3, 4);
    System.out.println("For Array Element 0:");
    obj[0].showData();
    System.out.println("For Array Element 1:");
    obj[1].showData();
  }
}

I am getting an below exception:

Exception in thread "main" java.lang.NullPointerException at ObjectArray.main(ObjectArray.java:24)

Please give me suggestion why this error has occurred?

Rajshree
  • 1
  • 2

1 Answers1

0
Account obj[] = new Account[2];

It'll allocate the memory for 2 objects of class 'Account'. For initializing those memory locations you have to choose either way:

Account obj[] = {new Account(), new Account()};
obj[0]=new Account();
obj[1]=new Account();
Shailendra Yadav
  • 1,612
  • 1
  • 9
  • 13