2

I'm trying to add a char to an ArrayList of Chars from an array of chars for reasons I won't talk about for fear of making the post long. I am using this basic code:

for(char ch: c){
    this.age.add(ch);
}

Where c is the array, and age is the ArrayList. Keep in mind that age is not initialized, therefore it is null. My question is, why am I getting a null pointer exception when I compile and run this?

5
  • this.age is null ? Do you have elements in c ? Commented Nov 28, 2013 at 7:36
  • The answer is in the question. age is not initialized, therefore it's null, therefore trying to call a method on it will throw a NullPointerException. Corollary: to avoid the exception, age needs to be initialized before calling any method on it. Commented Nov 28, 2013 at 7:37
  • yes. It is never initialized, therefore null. Commented Nov 28, 2013 at 7:37
  • So what would you initialize it to JB? first element zero? Commented Nov 28, 2013 at 7:38
  • You don't need to initialize any element inside the list. You just need to create the list, which is empty by default: age = new ArrayList<>(); Commented Nov 28, 2013 at 7:39

2 Answers 2

3

You are getting a nullpointer because age, the Arraylist is null. You need to initialize it before you add elements.

List<Character>  age = new ArrayList<Character>();
for(char ch: c){
    this.age.add(ch);
}

Initialize age before the for loop, if you do it in the for loop you will reinitialize it each time and lose your data.

Sign up to request clarification or add additional context in comments.

Comments

2

That might be you are not initialized age. initialize it like,

List<Character>  age = new ArrayList<Character>();

Exception coming because you just left it like

 List<Character>  age;

So by default reference is null. and calling a method on it's like

null.method()  //NullPointerException

2 Comments

ah I see. It's not initialized w/o the ending. Thanks!
@comscis Happens. Glad to help.

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.