Shakeeb Ayaz Shakeeb Ayaz - 1 year ago 146
Java Question

Difference between null and empty string

What is the difference between a null string (

String s = null
) and an empty string (
String s = ""

This is what I have:

String s1 = ""; //print statement does not print any thing for s1 but s1.length()=0
String s2 = null;//print statement prints "null" for s2 but s2.length() gives exception

What does it mean?

Answer Source

String s1 = ""; means that the empty String is assigned to s1. In this case, s1.length() is the same as "".length(), which will yield 0 as expected.

String s2 = null; means that (null) or "no value at all" is assigned to s2. So this one, s2.length() is the same as null.length(), which will yield a NullPointerException as you can't call methods on null variables (pointers, sort of) in Java.

Also, a point, the statement

String s1;

Actually has the same effect as:

String s1 = null;


String s1 = "";

Is, as said, a different thing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download