Marco Rosano
Marco Rosano

Reputation: 13

Java Exception in thread '"AWT-EventQueue-0"' java.lang.NullPointerException

I've got a class called Info and it's method load contains this piece code:

Circuito[] circuito=new Circuito[19];
for(int i=0;i<circuito.length;i++)
   circuito[i] = new Circuito(nome,immPath,sfondoPath,previsioni,giri,tempoGiro,carico);

I pass correctly all the parameters (I printed the toString() method to check if it works). Then, in another class called New I have this code:

Info info=new Info();
info.load();
System.out.println(info.getCircuito()[0].toString());

(The class Info contains the method getCircuito to returns the entire array).

then, I receive this error:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at New.<init>(New.java:21)

the line 21 is the System.out.print line.

I don't understand which is the problem...Thank you for your help!

Upvotes: 1

Views: 272

Answers (2)

Marco
Marco

Reputation: 1460

The only 3 possibilities for an NPE in the line

System.out.println(info.getCircuito()[0].toString());

are:

  • info is null. Not possible because you successfully call info.load() before.
  • getCircuito() returns null.
  • getCircuito()[0] is null.

That's it. So in your case with the code for load() shown it probably is the getCircuito() returning null.

Edit: Found the reason. You are calling

Circuito[] circuito=new Circuito[19];

in your load() method. Therefore you are assigning your new array not to the class variable but to a new variable in a local scope which is gone again after the load() method. Change said line to

circuito=new Circuito[19];

and you should be fine.

Upvotes: 2

PeakGen
PeakGen

Reputation: 23025

Definitely you are not filling your array due to some reason. May be you have defined the Circuito class instance of Info class inside a very narrow scope, something like a loop.

Try calling to another index inside your Info class. If that works, then the issue is with index 0.

Try getting the whole array and printing it. I guess the whole array will be NULL.

Finally, check whether you have used static keyword in unnecessary place.

Upvotes: 0

Related Questions