-1

I'm declaring an array of ints in the following way:

input = sc1.nextInt();
static int array [];

When I try to feed the array with a for loop, appears next message java.lang.NullPointerException.

This is the code:

for (int j=2; j<=input; j++){
    if (input%j==0) {
        array[counter1]=j;
        counter1++;
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 5
    You need to initialize it. `int[] array = new int[input];` – Unmitigated Jul 30 '21 at 16:13
  • Re, "I'm declaring... This is the code:..." Those variable declarations _are_ code. And the declaration of the class is code, and the declaration of the method that contains the `for` loop is code. The more you show the better. In fact, for such a simple example as this, you probably should just include the entire program, as well as the entire text of the error message. – Solomon Slow Jul 30 '21 at 16:20

2 Answers2

2

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*/ );
Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
1

Unlike other programming languages in java almost always you have to initialize your variable.

To initialize an array, you have to define a length for it. I don't know what are you trying to do but I'll give you an example:

int array[] = new int[10];

EDIT: I suggest you to give more attention to the @Solomon Slow answer, he explained it well!

Crih.exe
  • 502
  • 4
  • 16