187

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.

Lii
  • 11,553
  • 8
  • 64
  • 88
Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106
  • 7
    Compare with `b.equals(a)` -- but don't use `==` for string comparing as "it won't work" in other ways. The `null` value (which is different than an empty string `""`, a valid String instance) can *never* have a method invoked upon it. Placing the "known non-null" (usually a constant value or literal) to the left side of the equality is "Yoda conditionals" or some-such. –  Jan 26 '11 at 06:57

22 Answers22

384

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)

mikiqex
  • 5,023
  • 2
  • 24
  • 22
  • 14
    This is great! I was explaining null vs empty to somebody and happened upon your answer. The concept immediately clicked for them. – mfcallahan Mar 30 '18 at 01:40
  • i see a paper(not useful) on the left one :) – Michal - wereda-net Mar 15 '21 at 10:26
  • 1
    @Michal-wereda-net That would be less than a bit :-) But digging in memory usage I noticed the image actually illustrates another (yet implementation-dependent) information, that null and empty string both require the same (memory) space, occupied by its pointer: 4 bytes for 32-bit and 8 bytes for 64-bit. – mikiqex Mar 15 '21 at 14:02
  • that was lit :-O – Parthan_akon Mar 22 '21 at 04:45
247

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

pevik
  • 4,523
  • 3
  • 33
  • 44
Zach L
  • 16,072
  • 4
  • 38
  • 39
  • Does this apply to C# also? As in ""'s array is {'\0'}, a null – Cole Tobin Aug 17 '12 at 22:32
  • 3
    The link about `intern` has expired. You can reference to another site to read about it: https://weblogs.java.net/blog/enicholas/archive/2006/06/all_about_inter.html – Alston Aug 01 '14 at 05:30
  • So, if I have a null String `String a = null` and then I **append** it a String like `a+= "example"`, when I print it, why does display `nullexample` if null is not a String? – cpinamtz Jan 12 '18 at 11:43
  • @PinaGamer JavaScript allows adding non-strings to strings. `"num: " + 20` gives you the string `"num: 20"`. Does this mean that `20` is a string? (it's not, `20` is a number). Same case for `null`: it's not a string, but it can be converted to one if you try to add it. – daboross Mar 04 '18 at 09:13
  • @Zach L : when String s = null+"a"; it gives output nulla but null.concat("a") it gives the null pointer exception. what is the reason in my first case null+"a"; is working. – Onic Team Sep 14 '19 at 16:23
  • `null == "" = false` (expected) but in one of the strange quirks of the language, `0 == "" = true` (ummmm) – pstanton Sep 24 '20 at 11:41
18

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

Aba Dov
  • 962
  • 4
  • 12
  • 20
  • 1
    "null means that the String Object was not instantiated" - thank you! that helps me to understand things a lot. i was able to use an if statement on a MediaPlayer object once, and it worked to use null, to check if it was running or not (with a method to execute if it was), but i never understood why it worked, but now i see what it was saying, i was checking for whether MediaPlayer had been instantiated or not, by using null... e.g `if (mp==null){do something}`. – Azurespot May 18 '14 at 03:05
14

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.

Arkaaito
  • 7,347
  • 3
  • 39
  • 56
11

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.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
10

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

Community
  • 1
  • 1
  • 1
    Both `a` and `b` are references. `a` is a reference with an instantiated object. `b` is a reference without an instantiated object (hence the term "null reference"). – JUST MY correct OPINION Jan 26 '11 at 06:58
  • I counter-acted the -1 ;-) But it would help to clarify this answer and discuss the difference between "an object" and the `null` value and the difference between objects and variables. –  Jan 26 '11 at 07:00
  • @pst thanks :) I answered it by heart because here is my another answer that similar to this question http://stackoverflow.com/questions/4459623/java-is-null-an-instance-of-object/4459652#4459652 –  Jan 26 '11 at 07:04
9

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.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
7

enter image description here

This image might help you to understand the differences.

The image was collected from ProgrammerHumor

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
6

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.

JUST MY correct OPINION
  • 35,674
  • 17
  • 77
  • 99
5

"" 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());
    }
}

}

Siddhartha
  • 492
  • 1
  • 5
  • 15
5
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.

David
  • 3,166
  • 2
  • 30
  • 51
Mukesh Kumar
  • 317
  • 1
  • 5
  • 16
2

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.

weltraumpirat
  • 22,544
  • 5
  • 40
  • 54
2

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.

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
2

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 an empty value for it so it has a value even though that value is "";

str1 can be compared with other strings but str2 when compared will throw NullPointerException in RuntimeException.

Aaron Blenkush
  • 3,034
  • 2
  • 28
  • 54
Tashkhisi
  • 2,070
  • 1
  • 7
  • 20
1

In simple term,

  • "" is an empty String

  • null is an empty String Variable.

RoboAlex
  • 4,895
  • 6
  • 31
  • 37
0

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.

Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
0

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.

0

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
Neeraj Singh
  • 457
  • 7
  • 14
0

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.

Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
0

"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().

Shivakumar
  • 25
  • 8
0

as a curiosity

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

     s1 = s1 + s2;
   

    System.out.println((s); // nullhello
Java bee
  • 2,522
  • 1
  • 12
  • 25
0

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.

BlueJapan
  • 1,286
  • 2
  • 15
  • 16