Reputation: 8881
I have trying to access a static variable of class A in class B, however I am getting NullPointerException. The code is :
public class OutgoingMessage {
public static SMPPSession session;
public static void main(String [] args)
{
session = new SMPPSession();
}
}
And
public class SendSMS {
public static void main(String [] args)
{
if(OutgoingMessage.session.getSessionState().toString().equals("Connected"))//Line 44
{
}
}
}
The error reads
Exception in thread "main" java.lang.NullPointerException
at SendSMS.main(SendSMS.java:44)
Any idea what am I missing ?
Thanks
Satya
Upvotes: 0
Views: 2923
Reputation: 57
You can add OutgoingMessage.main(args);
before:
if(OutgoingMessage.session.getSessionState().toString().equals("Connected")) //Line 44 ...
Upvotes: 1
Reputation: 213263
You haven't initialized your static variable.. That's why..
Actually you have done that in main()
, but that will really not affect your output.. As your main will never be run.. You can initialize it at the place of declaration only..
public static SMPPSession session = new SMPPSession();
Before main method.. But it doesn't make sense to have it as static variable..
You should declare it as instance variable and initialize it for each instance you create using a Constructor
..
Upvotes: 0
Reputation: 2793
The problem is when you use OutgoingMessage.session
it is not yet initialized. To correctly initialize it do:
public class OutgoingMessage {
public static SMPPSession session = new SMPPSession();
}
Upvotes: 0
Reputation: 2727
You are missing a static getter method in OutgoingMessage, and you only need one main method.
Upvotes: 0
Reputation: 1500665
Sure - you're using OutgoingMessage.session
, which will be null unless you've also run OutgoingMessage.main
. It's not like main
methods get invoked automatically everywhere - that's just the entry point for the application.
I suggest that instead of changing this to use a static initializer or something like that, you try to work to avoid static variables.
Why would it make sense for OutgoingMessage
to have a static session
variable? I'd expect the two to work together, not one be composed of the other... for example, I could imagine:
SMPPSession session = new SMPPSession();
session.send(outgoingMessage);
or even:
SMPPSession session = new SMPPSession();
outgoingMessage.sendInSession(session);
Upvotes: 6
Reputation: 66637
OutgoingMessage.session
is null
at the point where you are calling
if(OutgoingMessage.session.getSessionState()
Which results in NullPointerException
.
Make sure OutgoingMessage
class main
method is executed before making if(OutgoingMessage.session.getSessionState()
Unless you use OutgoingMessage as main class, it doesn't make sense to define main method there, which confuses more.
Upvotes: 2