1

My code shows null pointer exception when i assign values to int array in the object:

public class Cage {
    int Value;  
    String Operator;
    int[] placeHolders;
}

Cage o = new Cage();                
o.Value = Integer.parseInt(strSplit[0]);
o.Operator = strSplit[1];               
for(int i=2;i<strSplit.length;i++) {
    o.placeHolders[i] = Integer.parseInt(strSplit[i]);
}
2
  • 7
    Where do you initialise placeHolders so it is not null? Commented Sep 21, 2012 at 8:42
  • 1
    You should read the Arrays section of the Java Tutorial, especially the parts about Declaring a Variable to Refer to an Array and then Creating, Initializing, and Accessing an Array Commented Sep 21, 2012 at 8:45

3 Answers 3

4

You should create an int array for your placeHolders, it's just a declaration, not a definition right now.

o.placeHolders = new int[strSplit.length];
Sign up to request clarification or add additional context in comments.

3 Comments

You could make the size of the array strSplit.length - 2 as the first 2 elements from strSplit don't go in placeHolders.
But in that case the array index should changed, in the example it's not zero based.
Yep, so I suppose it just depends on whether the OP wants a gap at the start of the array.
2

I guess that you want to have placeHolders to hold values without null values in the first to indexes.

o.placeHolders = new int[strSplit.length - 2];
for (int i = 0; i < strSplit.length - 2; i++) {
    o.placeHolders[i] = Integer.parseInt(strSplit[i + 2]);
}

Comments

0

You should instantiate the int[] object before using it:

int[] placeHolders = new int[100];

4 Comments

int[100] is hard coding.. i guess not a very good style . thx for helping though
@V.J. The you should use a list: List<Integer> placeHolders = new ArrayList<Integer>();
But in this case an array is fine because you know the size required from the length of strSplit.
@mikej then you instantiate the array object with that particular length; anyway, the problem was that the object was not instantiated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.