• Post Reply Bookmark Topic Watch Topic
  • New Topic

NullPointerException  RSS feed

 
Preethi Chilukuri
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.ArrayList;
class ThrowNullPointerException {
static ArrayList<String> list = null;
public static void main(String[] args) {
list.add("Apple");
}
}


Why is "NullPointerException" thrown and string "Apple" not being added as list(0)?
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NullPointerException is being thrown because 'list' is null. You can't use 'list' until an ArrayList reference is assigned to it.

Do you understand what null means?
 
Ashwin Rao
Ranch Hand
Posts: 89
C++ Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NullPointerException is being thrown because the ArrayList reference "list" is not pointing to an object.
The reference is just a way to get the object. You actually add "Apple" to the ArrayList object using the reference but your reference does not point to any object. Hence you get the exception.
 
Preethi Chilukuri
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it. Thanks for the prompt response
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You get a NullPointerException when you try and dereference a reference when it points to null. This means any time you use the '.' operator to call a method. If the reference is to an array it also includes using '[]' to access an element.

In your first example you tried to access an element in an array that was null.

In your second example the array was not null, so you did not get a NullPointerException.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!