-1

I wrote this statement in the main method the Exception will be in the (GuaranteeYears) so i put it in the try block.

First in the main I make a Store object and pass number 4 in parameter, in the Store class I will have a array called arrProduct that will have the length 4:

boolean flag1 = true;
while (flag1) {
    try {
        System.out.println("Ente GuaranteeYears");
        int GuaranteeYears=read.nextInt();

        StrongDevice s = new StrongDevice(code,type,price,Model,Capacity,GuaranteeYears); //the object

        flag1 = false;
        x.addProduct(s);
     }

and this is my add method

public boolean addProduct(Product p) {
    if(arrProduct.length==NumOfProduct)
        return false;

    arrProduct[NumOfProduct]=p;
    NumOfProduct++;
    return true;
}

My question is: when I make the object and add it to the array it gives me NullPointerException - why that happened?

Alexey Malev
  • 6,408
  • 4
  • 34
  • 52
BSMN
  • 5
  • 1
  • 4
  • @SotiriosDelimanolis I really know what is Null pointer Exception , but I don't know why its happened here ? – BSMN Apr 15 '14 at 19:22
  • There aren't a million reasons for NPE to happen. Read the answer. You will find out why it happens and you can apply that to your scenario. – Sotirios Delimanolis Apr 15 '14 at 19:23

1 Answers1

0

As far as I understood, the line which cause NPE is

x.addProduct(s);

Most likely this is caused by array arrProduct which is not initialized and cause NPE when it is being accessed.

To fix that, please verify that arrProduct is always correctly initialized at Store object creation.

Alexey Malev
  • 6,408
  • 4
  • 34
  • 52