Reputation: 735
I do not know why but this line of code gives a NullPointerException
. I searched creating array of an user obj. in Java, again but, I could not find any problem.
private State[] states;
.
.
.
private void initializeStates( )
{
states = new State[ stateNames.length ]; // Throws NullPointerException
for( int i = 0; i < stateNames.length; i++ )
{
states[i] = new State();
states[i].setName( stateNames[i] );
states[i].setColor( stateColors.getColor() );
}
} // End of initializeStates()
And here is the class:
public class State
{
private String stateName;
private String color;
private boolean isStartState;
private boolean isFinalState;
State()
{
stateName = new String(); // Can this line cause nullPtrException?
color = new String(); // Can this line cause nullPtrException?
isStartState = false;
isFinalState = false;
}
public void setName( String name ){ stateName = name; }
public void setColor( String clr ) { color = clr; }
public void makeStart( ) { isStartState = true; }
public void makeFinal( ) { isFinalState = true; }
}
Upvotes: 0
Views: 140
Reputation: 1500085
If this line throws the exception:
states = new State[ stateNames.length ]; // Throws NullPointerException
... then the problem is that stateNames
is null
. You're not making it as far as any of the rest of your code.
You haven't shown where stateNames
is declared or initialized, but that's where you should look next.
As an aside, this:
stateName = new String();
... is inefficient for no reason. Just use an empty string literal:
stateName = "";
(Or better, take the appropriate initial values as constructor parameters.)
Upvotes: 5