5
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by hfx642
1

When you try to use a reference variable or expression that does not contain a reference to an Object - ie contains null. This may be because it hasn't been initialised, or it may be the result of calling a method that returns null following an error or other condition such as end-of-file.

0

A NPE will also occur if an object is defined (and also initialized) inside one method,
and you try to access it from another method.
Solution: Define the object outside of the method (to make it global).

0

@hfx642: No, the situation you describe would not compile. The variable would have no scope outside the method in which it was declared. It would complain "Cannot find symbol"

0

@hfx642: To add to what ezzaral said, variable is not available is correct , but then you may pass it as a parameter , even when you pass that as a parameter, since u say it has been initialized, it will not throw a NPE,unless you specifically initialize it to a NULL.

Also, use of global variables is not at all advised. There may be instances where you may need a few of them , but should not be used everywhere. Passing the variables/references and using them is the most judicious way.

Edited by adarshcu: n/a

0

Yes... You are right... Let me think... Oh, yeah...
If you define an object in a method, then use it in a listener,
the listener can't access the object.
eg. Using a JComboBox to alter the text in a JLabel.
If the JLabel is not globally defined, the listener can't alter it.
NPE!

0

If the JLabel is not globally defined, the listener can't ... refer to it in its source code. You'll get a compiler "Cannot find symbol". It won't get to execute, so still no NPE.

0

Alright... Just ignore all of my posts for the moment.
I know there is SOMETHING about this, when I have an object declared AND initialized and I still get a NPE, if I declare it globally, the NPE error goes away.
I just can't think of it at the moment.
...
Carry on!!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.