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. For example, “programming” is a String. Java programming language supports Strings, and they are treated as objects. String class is immutable. Therefore, after creating an object, it cannot be changed. Sometimes, Strings can be null or empty. When String variable is assigned with null, it indicates that the variable is not actually referring to any memory location in the heap. However, when a String variable is assigned with an empty String, it indicates that the reference variable is referring to a memory location of a string with zero length.
Key Areas Covered
Empty, Null, Strings
What is null
Null refers to nothing. Observe the below two Statements.
s1 is a String variable. It is assigned with null. Therefore, the JVM will not allocate any memory, so the variable s1 will not point to anything The statement String s1 = null; is also equivalent to String s1; When printing the length of the String s1, it will give a null pointer exception. This is because the s1 does not refer to an actual string to count the length.
What is empty
Empty refers to a string with no length. Refer the below code.
s2 is a String variable. It is assigned with an empty string which is “”. Therefore, the JVM will allocate memory space for an empty string. s2 will refer to that empty string. When printing the length of the String s2, it will print 0. That is because s1 is pointing to a String, but it does not have any characters to count the length.
Difference Between null and empty
The null is a term that indicates an object is referring to nothing in the heap while empty is a term that indicates an object is referring to a unique string of length zero in the heap.
String s1= null; or String s1; expresses that s1 is referring to nothing or null. String s2= “”; expresses that s2 is referring to an empty string.
Printing the length of the null string will give a null pointer exception. Printing the length of the empty string will give a zero.
A String refers to a sequence of characters. Strings can sometimes be null or empty. The difference between null and empty is that the null is used to refer to nothing while empty is used to refer a unique string with zero length.
Tutorials Point. “Java Strings.” Www.tutorialspoint.com, Tutorials Point, 12 Aug. 2018, Available here.