It's hard to know for sure because you left out so much of your program, but @unmitigated probably is correct: The exception probably was thrown from this line, array[counter1]=j;
because array
probably was null
.
Your array
variable is not an array. Java arrays and Java objects are never stored in variables. They can only exist on the heap, and Java variables can only hold references to arrays and objects. Your program must first explicitly create the array before it can use it. Just like how @unmitigated showed you:
array = new int[input];
The new
operator creates a new object or, as in this case, a new array on the heap, and it returns a reference to the new thing. Then, the assignment operator, =
, stores the reference into your array
variable.
Same goes for objects: If your program has some class Foobar
, and a Foobar
variable, then it must explicitly create an instance and assign it to the variable before the variable can be used.
Foobar myFoo;
...
myFoo = new Foobar( /*constructor arguments, if any, go here*/ );