0

If I declare Arraylist like this-

private ArrayList<Integer[]> nodeList;

then, while adding array into it, getting NullPointerException

But, if I change it to-

private ArrayList<Integer[]> nodeList= new ArrayList<Integer[]>();

-it works fine.

Why the first one fails!

3
  • 1
    As you state, in first case you declare it only, but its initial value is null. Commented Nov 9, 2011 at 15:41
  • 1
    @Avisek stackoverflow.com/questions/8065763/… :) no offense but you should read some books about programming in java Commented Nov 9, 2011 at 15:46
  • ya am a noob & am clarifying while trying exercises. Actually, its much confusive to switch to JAVA from PHP Commented Nov 9, 2011 at 16:29

1 Answer 1

3

The first only declares a variable, but does not create the actual object. only when you use new, you actually create the object.

In java unlike C++, declaring a variable does not allocate a local variable of it. To actually create the object, you need to explicitly create it [in your example: by using the new keyword].
(*)Note that this is only true to reference types objects, and java primitives are created with declaration.

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

Comments

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.