Wednesday, February 6, 2013

Difference between NULL and empty string in Java

What is difference between null string (String abc = null) and empty string (String abc = "") ?

Analysis:
--------
Try to call a method on both of them and you'll see the difference


  1. String s = "";   s.length();  
you actually declare a new String Object, and it means the variable (in this case - s) has a String Object associated to it. you can call String methods on that object.
it is like typing:
              String s = new String();
  if you type:   String s = "";   s.lentgh; // return 0  

   2.   String s = null;   s.length();
    s.lentgh;//returns a null pointer exception

 Basically a reference to an empty string points to an object in the heap so you can call methods on it. But a reference pointing to null has no object to point in the heap and thus you'll get a Null Pointer Exception


1 comment: