-2

I want to make a table as an attribute and retrieving it was successful but it comes with an error

public class Main {
    public static class stock {
        public int n;
        public int t[];
        public stock(int n)
        {
            t=new int[n];
        }
        public void display()
        {
            for(int i:t)
            {
                System.out.print(i+"   ");
            }
        }
    }
    public static void main(String[] args) {
       stock s=new stock(4);
        stock c[] =new stock[4];
        for(int j=0;j<2;j++)
        {
        for(int i=0;i<4;i++)
        {
            s.t[i]=i;
        }
        c[j]=s;
        }
        for(stock x:c)
            x.display();
    }
}

this is the result with an error how can i get rid of it where is the problem Error1

user
  • 7,435
  • 3
  • 14
  • 44
  • Please look at a Java tutorial and learn about Java's conventions. The field `n` never seems to be set, and the array `c` isn't filled up properly – user May 25 '20 at 22:08
  • 1
    In this line of code `for(int j=0;j<2;j++)` you are only assigning two of the four initialized `Stock` array objects. So the last two are `NULL`. But in this line of code `for(stock x:c)` you iterate over all four...two are `NULL` objects. There it is. – Barns May 25 '20 at 22:10

1 Answers1

1

In the end, c will contain only a single instance. When you write c[j] = s, the object is not copied, but its reference is. You will display the same object multiple times. The NPE is due to your c array only being assigned 2 items, but then iterating its maximum capacity 4 (index 0 and 1 pointing to s, index 2 and 3 being still null).

knittl
  • 246,190
  • 53
  • 318
  • 364