-2

Why the below code throws null pointer excetion in test.put(1,"sd")

public class HashMap {
  @SuppressWarnings("null")
  public static void main(String a[]){
    Map test = null;
    test.put(1, "sd");  
    System.out.println(test);
  }
}
dimo414
  • 47,227
  • 18
  • 148
  • 244
user3839699
  • 21
  • 1
  • 5

1 Answers1

0

Because test is null.

Map test = null;

Try instantiating the map instead.

Map test = new HashMap();

Or try a parameterized map:

Map<Integer,String> test = new HashMap<Integer,String>();
nostromo
  • 1,435
  • 2
  • 17
  • 23
  • but then i am inserting value -- test.put(1, "sd"); Then y an exception – user3839699 Sep 18 '14 at 04:59
  • You can't insert a value into a null object. The object must exist before you can add a value. – nostromo Sep 18 '14 at 05:01
  • @user3839699 what, exactly, do you think you are inserting a value *into*? You haven't created a `Map` to put your data in - you're explicitly using `null`.... – dimo414 Sep 18 '14 at 05:01