Difference between null and empty ("") Java String

JavaStringNullEqualsReferenceequals

Java Problem Overview


What is the difference between null and the "" (empty string)?

I have written some simple code:

String a = "";
String b = null;

System.out.println(a == b); // false
System.out.println(a.equals(b)); // false

Both statements return false. It seems, I am not able to find what is the actual difference between them.

Java Solutions


Solution 1 - Java

You may also understand the difference between null and an empty string this way:

Difference between null and 0/empty string

Original image by R. Sato (@raysato)

Solution 2 - Java

"" is an actual string, albeit an empty one.

null, however, means that the String variable points to nothing.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) returns false because "" does not equal null, obviously.

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

and so on.

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()


If the difference you are wondering about is == versus equals, it's this:

== compares references, like if I went

String a = new String("");
String b = new String("");
System.out.println(a==b);

That would output false because I allocated two different objects, and a and b point to different objects.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

Be warned, though, that Java does have a special case for Strings.

String a = "abc";
String b = "abc";
System.out.println(a==b);

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

Solution 3 - Java

String is an Object and can be null

null means that the String Object was not instantiated

"" is an actual value of the instantiated Object String like "aaa"

Here is a link that might clarify that point http://download.oracle.com/javase/tutorial/java/concepts/object.html

Solution 4 - Java

What your statements are telling you is just that "" isn't the same as null - which is true. "" is an empty string; null means that no value has been assigned.

It might be more enlightening to try:

System.out.println(a.length()); // 0
System.out.println(b.length()); // error; b is not an object

"" is still a string, meaning you can call its methods and get meaningful information. null is an empty variable - there's literally nothing there.

Solution 5 - Java

There is a pretty significant difference between the two. The empty string "" is "the string that has no characters in it." It's an actual string that has a well-defined length. All of the standard string operations are well-defined on the empty string - you can convert it to lower case, look up the index of some character in it, etc. The null string null is "no string at all." It doesn't have a length because it's not a string at all. Trying to apply any standard string operation to the null string will cause a NullPointerException at runtime.

Solution 6 - Java

here a is an Object but b(null) is not an Object it is a null reference

System.out.println(a instanceof Object); // true

System.out.println(b instanceof Object); // false

here is my similar answer

Solution 7 - Java

null means the name isn't referencing any instantiated object. "" means an empty string.

Here a is referencing some object which happens to be an empty string. b isn't referencing any object as it's null.

Solution 8 - Java

In Java a reference type assigned null has no value at all. A string assigned "" has a value: an empty string, which is to say a string with no characters in it. When a variable is assigned null it means there is no underlying object of any kind, string or otherwise.

Solution 9 - Java

"" and null both are different . the first one means as part of string variable declaration the string constant has been created in the string pool and some memory has been assigned for the same.

But when we are declaring it with null then it has just been instantiated jvm , but no memory has been allocated for it. therefore if you are trying to access this object by checking it with "" - blank variable , it can't prevent nullpointerexception . Please find below one use-case.

public class StringCheck {

public static void main(String[] args) {
	// TODO Auto-generated method stub

	String s1 = "siddhartha";
	String s2 = "";
	String s3 = null;

	System.out.println("length s1 ="+s1.length());
	System.out.println("length s2 ="+s2.length());

	//this piece of code will still throw nullpointerexception . 
	if(s3 != ""){
		System.out.println("length s3 ="+s3.length());
	}
}

}

Solution 10 - Java

String s = "";
s.length();

String s = null;
s.length();

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 NullPointerException.

Solution 11 - Java

enter image description here

This image might help you to understand the differences.

The image was collected from ProgrammerHumor

Solution 12 - Java

> The empty string is distinct from a > null reference in that in an > object-oriented programming language a > null reference to a string type > doesn't point to a string object and > will cause an error were one to try to > perform any operation on it. The empty > string is still a string upon which > string operations may be attempted.

From the wikipedia article on empty string.

Solution 13 - Java

String s=null;

String is not initialized for null. if any string operation tried it can throw null pointer exception

String t="null";

It is a string literal with value string "null" same like t = "xyz". It will not throw null pointer.

String u="";

It is as empty string , It will not throw null pointer.

Solution 14 - Java

A string can be empty or have a null value. If a string is null, it isn't referring to anything in memory. Try s.length()>0. This is because if a string is empty, it still returns a length of 0. So if you enter nothing for the same, then it will still continue looping since it doesn't register the string as null. Whereas if you check for length, then it will exit out of it's loop.

Solution 15 - Java

This concept can be better understood from mathematics. Have you ever tried dividing a number (not zero) by 0 using a calculator e.g 7/0? You will get a result that looks like something this: undefined, not a number, null etc. This means that the operation is impossible, for some reasons (let's leave those reasons to be discussed another day).

Now, perform this: 0/7. You will get the output, 0. This means that the operation is possible and can be executed, but you the answer is just 0 because nothing is left after the division. There is a valid output and that output is zero.

In the first example, not only was the output invalid, the operation was not possible to execute. This is akin to null string in java. The second example is akin to empty string.

Solution 16 - Java

When you write

String a = "";

It means there is a variable 'a' of type string which points to a object reference in string pool which has a value "". As variable a is holding a valid string object reference, all the methods of string can be applied here.

Whereas when you write

String b = null;

It means that there is a variable b of type string which points to an unknown reference. And any operation on unknown reference will result in an NullPointerException.

Now, let us evaluate the below expressions.

System.out.println(a == b); // false. because a and b both points to different object reference

System.out.println(a.equals(b)); // false, because the values at object reference pointed by a and b do not match.

System.out.println(b.equals(a)); // NullPointerException, because b is pointing to unknown reference and no operation is allowed

Solution 17 - Java

In simple term,

  • "" is an empty String

  • null is an empty String Variable.

Solution 18 - Java

Difference between null & empty string. For example: you have a variable named x. If you write in JS,

var x = "";

this means that you have assigned a value which is empty string (length is 0). Actually this is like something but which is feel of nothing :) On the other hand,

var y = null;

this means you've not assigned a value to y that clearly said by writing null to y at the time of declaration. If you write y.length; it will throw an error which indicates that no value assigned to y and as a result can't read length of y.

Solution 19 - Java

"I call it my billion-dollar mistake. It was the invention of the null reference in 1965" - https://en.wikipedia.org/wiki/Tony_Hoare

With respect to real world both can be assumed same. Its just a syntax of a programming language that creates a difference between two as explained by others here. This simply creates overhead like when checking/comparing whether string variable has something, you have to first check if its not null and then actual string comparing ie two comparisons. This is a waste of processing power for every string comparisons.

Objects.equals() checks for null before calling .equals().

Solution 20 - Java

as a curiosity

    String s1 = null;
    String s2 = "hello";

     s1 = s1 + s2;
   

    System.out.println((s); // nullhello

Solution 21 - Java

null means nothing; it means you have never set a value for your variable but empty means you have set "" value to your String for instance see the following example:

String str1;
String str2 = "";

Here str1 is null meaning that you have defined it but not set any value for it yet, but you have defined str2 and set empty value for it so it has a value even that value is "";

but

Solution 22 - Java

Amazing answers, but I'd like to give from a different perspective.

String a = "StackOverflow";
String a1 = "StackOverflow" + "";
String a2 = "StackOverflow" + null;

System.out.println(a == a1); // true
System.out.println(a == a2); // false

So this can tell us "" and null point to the different object references.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVikas PatidarView Question on Stackoverflow
Solution 1 - JavamikiqexView Answer on Stackoverflow
Solution 2 - JavaZach LView Answer on Stackoverflow
Solution 3 - JavaAba DovView Answer on Stackoverflow
Solution 4 - JavaArkaaitoView Answer on Stackoverflow
Solution 5 - JavatemplatetypedefView Answer on Stackoverflow
Solution 6 - Javauser467871View Answer on Stackoverflow
Solution 7 - JavaShamim Hafiz - MSFTView Answer on Stackoverflow
Solution 8 - JavaJUST MY correct OPINIONView Answer on Stackoverflow
Solution 9 - JavaSiddharthaView Answer on Stackoverflow
Solution 10 - JavaMukesh KumarView Answer on Stackoverflow
Solution 11 - JavaSazzad Hissain KhanView Answer on Stackoverflow
Solution 12 - JavaweltraumpiratView Answer on Stackoverflow
Solution 13 - JavaBharat KasodariyaView Answer on Stackoverflow
Solution 14 - JavaBibianaView Answer on Stackoverflow
Solution 15 - Javauser8715994View Answer on Stackoverflow
Solution 16 - JavaNeeraj SinghView Answer on Stackoverflow
Solution 17 - JavaRoboAlexView Answer on Stackoverflow
Solution 18 - JavaRashed RahatView Answer on Stackoverflow
Solution 19 - JavaShivakumarView Answer on Stackoverflow
Solution 20 - JavaJavaView Answer on Stackoverflow
Solution 21 - JavaTashkhisiView Answer on Stackoverflow
Solution 22 - JavaBlueJapanView Answer on Stackoverflow