Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between null and empty string [duplicate]

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?

like image 635
Shakeeb Ayaz Avatar asked May 18 '13 03:05

Shakeeb Ayaz


People also ask

Is empty string better than null?

So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

IS null same as empty?

The main difference between null and empty is that the null is used to refer to nothing while empty is used to refer to a unique string with zero length. A String refers to a sequence of characters.

Is null and empty string the same in SQL?

Much like Zero, an Empty String ("") differs from a NULL value in that the former specifically implies that the value was set to be empty, whereas NULL means that the value was not supplied or is unknown. As an example, let's consider a column that stores a cell phone number.

What is the difference between null value and empty value?

In database terms, however, a null value is a value that doesn't exist: the field does not contain a value of any kind (not even a blank value). By contrast, a blank value is a real value: it just happens to be a string value containing 0 characters.


1 Answers

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; 

Whereas

String s1 = ""; 

Is, as said, a different thing.

like image 81
acdcjunior Avatar answered Oct 07 '22 22:10

acdcjunior