java - Why am I receiving a null pointer exception? -


when call calculatestringvalue method on string within main method, works fine. when try call method within printstringswithvalues method, null pointer exception. have string being in arraylist?

public static void main(string[] args){      list<string> testlist = new arraylist<>();     testlist.add("apple");     testlist.add("hello");     printstringswithvalues(testlist);}   public static void printstringswithvalues(list<string> strings) {     (string string : strings) {          system.out.println(string + ",    " + calculatestringvalue(string));     } }  public static int calculatestringvalue(string word) {     int value = 0;      for(int j=0; j < word.length(); j++)     {         if(lettervaluemap.containskey(word.charat(j)))         {             value += lettervaluemap.get(word.charat(j));         }             else{             return -1;         }     }     return value;  } 

using contextual inference of type of lettervaluemap assume map<character, integer>, tried create such kind of map , assign arbitrary values in order test code.

here did

first declare lettervaluemap variable , feed values using static initialization block

public class nullpointerhandler {      private static map<character, integer> lettervaluemap;     static {         lettervaluemap = new hashmap<character, integer>();         (int = 'a'; i<= 'a'+25; i++) {             lettervaluemap.put((char)i, i);         }          (int = 'a'; i<= 'a'+25; i++) {             lettervaluemap.put((char)i, i);         }          lettervaluemap.put(' ', 32);     } 

then use other part of code unchanged (except have added few more words testing purpose)!

        public static void main(string[] args){              list<string> testlist = new arraylist<string>();             testlist.add("apple");             testlist.add("hello");             testlist.add("rome");             testlist.add("rome");             testlist.add("julius cesar");             printstringswithvalues(testlist);         }          public static void printstringswithvalues(list<string> strings)         {             (string string : strings) {              system.out.println(string + ",    " + calculatestringvalue(string));         }     }      public static int calculatestringvalue(string word)     {         int value = 0;          for(int j=0; j < word.length(); j++)         {             if(lettervaluemap.containskey(word.charat(j)))             {                 value += lettervaluemap.get(word.charat(j));             }                 else{                 return -1;             }         }         return value;      }  } 

testing gives me expected results, without generating null pointer exception

no null pointer