0

This is not working (Throwing Nullpointer Exception)

String s =  null; 
System.out.println(s); 
System.out.println(String.valueOf(null));

But this is

String s =  null; 
System.out.println(s); 
System.out.println(String.valueOf(s));

why ?? unable to getting. I want understand logic behind.

luk2302
  • 55,258
  • 23
  • 97
  • 137
Mukesh
  • 921
  • 10
  • 23

1 Answers1

5

String.valueOf(null) calls valueOf(char data[]) which in turn calls new String(data) which accesses value.length -> NPE.

String.valueOf(someString) calls valueOf(Object obj) which does return (obj == null) ? "null" : obj.toString();


General note: please use a proper IDE. This was not my "knowledge" writing this question but just me using my IDE for ~1 minute to see which methods will actually be called, I did not even run the code.

luk2302
  • 55,258
  • 23
  • 97
  • 137