Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Change values of an array by a method in a Class

Here is my code:

class Myclass {

    private static int[] array;

    public static void main(String[] args) {
        Myclass m = new Myclass();

        for (int i = 0; i < 10; i++) {
            m.array[i] = i;
            System.out.println(m.array[i]);
        }
    }

    public Myclass() {
        int[] array = new int[10];
    }
}

It throws a java.lang.nullPointerException when trying to do this:

m.array[i] = i;

Can anybody help me please?

like image 373
philipp94831 Avatar asked Nov 25 '25 01:11

philipp94831


1 Answers

You have declared a local variable array in your constructor, so you're not actually initializing the array declared in Myclass.

You'll want to refer directly to array in the constructor. Instead of

int[] array = new int[10];

Use this

array = new int[10];

Additionally, you've declared array static in the scope of your Myclass class.

private static int[] array;

You only have one instance of Myclass here, so it doesn't matter, but normally this would not be static, if you're initializing it in a constructor. You should remove static:

private int[] array;
like image 174
rgettman Avatar answered Nov 26 '25 16:11

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!