Why does Java throw NullPointerException here?
Solution 1:
what you did is called shadowing you shadowed your field x
with local variable x
. so all you need to do is avoiding this:
int[] x = new int [N];
is wrong, if you want your field to initialize instead of a local variable then you could do something like : x = new int [N];
for more information read this
Solution 2:
change the first line in constructor from
int[] x = new int [N];
to
x = new int [N];
it should work...
Actually in constructor when you say int[] x, it is creating one more local variable instead setting data to public variable x... if you remove int[] from first line of constructor then it initizes the public variable & you will be able to print them in main() method
Solution 3:
Inside public Test(int n)
:
Change
int[] x = new int [N]; // Creating a local int array x
to
x = new int [N]; // Assigning it to x
Solution 4:
Everyone has given the code that would work. But the reason is something called as variable scoping. When you create a variable (by saying int[] x, you are declaring x as an integer array and by saying x = new int[4] you are assigning a new array to x). If you use the same variable name x everywhere and keep assigning things to it, it'll be the same across your class.
But, if you declare int[] x one more time - then you are creating one more variable with the name x - now this can result in duplicate variable error or if you're declaring in a narrower 'scope', you will be overriding your previous declaration of x.
Please read about java variable scopes to understand how scoping works.