Tutorial :null = “” for a string



Question:

In Java are these 2 statements the same?

String a = null;  String b = "";  

It feels a bit of a dumb question but have a complete mental block currently.


Solution:1

The empty string and null are different. The empty string is a string with no characters, null is not having a string at all.

You can call methods on an empty string but if you try to call a method on null you will get an exception.

public static void main(String[] args)  {      String a = null;      String b = "";      System.out.println(b.length());      System.out.println(a.length());  }  

Output:

  0  Exception in thread "main" java.lang.NullPointerException          at Program.main(Program.java:12)  


Solution:2

No, an empty string is not null.


Solution:3

They are most definitely not the same. Your String variable acts as a reference to an object in memory, and if it's set to null, it's not pointing to anything. If it's set to the empty-string value, it's pointing to that.

In my own coding, I generally set a String to "" instead of to null unless I have a special need for null. There are some libraries like Apache Commons that include helper classes like StringUtils that will collapse a check for null, the empty string, and even just whitespace into one call: StringUtils.isBlank(), StringUtils.isNotBlank(), etc. Pretty handy. Or you can write your own helper methods to do similar pretty easily.

Good luck as you progress in Java!


Solution:4

The third possibility is:

String c;  

All three are different, of course.


Solution:5

this is not as dumb as it sounds. it bothers even seasoned programmers. in many real world projects people often write something like if(s==null || s.isEmpty()), i.e. people treat null and "" as semantically equivalent .


Solution:6

null means it refers to nothing, while empty string is a special string with zero length.


Solution:7

String a = null;
String b = "";

The first statement in java initialises a variable handle. there is no memory allocated for data to be saved.

The second statement shows two objects the first object being the handle (b) and second object being "" (if we ignore the higher concepts of string pooling in java where string is mutable and jvm gives out pooled instances of string)

thus the two lines are not same.


Solution:8

No, They are different. If you use a null String in a method, then Exception occur But not occur in a empty String!


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »