1

There are a lot of questions about null and in java.

What I am failing to grasp is what people mean by null is pointing to nothing or why to use null at all.

I can't understand the difference between

String thing = null;

and

String thing = "";

This question has detailed answers What is null in Java?, but I just can't wrap my head around it.

What am I missing?


languages I've studied (no expert)

Python, vb (vb.net), web programming (html, css, php, bit of js), sql

I should add, it is this answer https://stackoverflow.com/a/19697058/2776866 which prompted me to write this.

Community
  • 1
  • 1

9 Answers9

6
String str = null;

means a String reference, named str, not pointing to anything

String str = "";

means a String reference, named str, pointing to an actual String instance. And for that String instance, it is a zero-length String, but it is still an actual object.


Just a little update with some diagram which hopefully can help you visualize that:

assume I have

String nullStr = null;
String emptyStr = "";
String myStr = "ab";

What it conceptually is something look like:

  // String nullStr = null;

  nullStr ----------> X    pointing to nothing



  // String emptyStr = "";
                      +------------------+
  emptyStr ---------> |       String     |
                      +------------------+
                      | length = 0       |
                      | content = []     |
                      +------------------+


  // String myStr = "ab";
                      +------------------+
  myStr ------------> |       String     |
                      +------------------+
                      | length = 2       |
                      | content = [ab]   |
                      +------------------+

(of course the internal structure of the String object is not the real thing in Java, it is just for giving you an idea)


More edit for the rationale behind NULL:

In fact in some language they do not provide concept of NULL. Anyway, in Java (or similar language), Null means semantically different from "empty" object. Use String as an example, I may have a People class with a String preferedTitle attribute. A Null preferedTitle means there is NO preferred title for that people (so that we need to derive and show the title for it, maybe), while a preferedTitle being an empty string means there IS a preferred title, and that's showing nothing.

Btw, although a bit off topic: concept of Null is seen as problematic for some people (because all those extra handling it need etc). Hence some languages (e.g. Haskell) are using some other ways to handle the situation where we used to use Null.

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
  • 1
    Lemme draw a little ascii art and wish it help you visualize that, just a moment – Adrian Shum Oct 31 '13 at 02:08
  • @Skippy: that's a good question. In fact in some language they do not provide concept of NULL. Anyway, in Java (or similar language), Null means semantically different from "empty" object. Use String as an example, I may have a `People` class with a String `preferedTitle` attribute. A Null `preferedTitle` means there is NO preferred title for that people (so that we need to derive and show the title for it, maybe), while a `preferedTitle` being an empty string means there IS a preferred title, and that's showing nothing. – Adrian Shum Oct 31 '13 at 02:20
  • btw, concept of Null is seen as problematic for some people (because all those extra handling it need etc). Hence some languages (e.g. Haskell?) are using some other ways to handle the situation where we used to use Null. – Adrian Shum Oct 31 '13 at 02:23
4

Java doesn't really expose pointers, instead it deals with references.

When you say

String thing = null;

You are saying that there is a reference (of type string) called thing, which isn't referencing anything.

When you say

String thing = ""

This is shorthand for,

String thing = new String("");

Now you have an actual object initialized and ready to be used. You told the compiler to create a string and now your "thing" references the new string.

If you want to know the length of your initialized string, you can go;

thing.length

Which is zero. The string exists, but is zero length.

Trying string.length on the null version causes a NullReferenceException, which is the compiler saying

"I tried to find out about the length of your string, but I couldn't find it!"

Resorath
  • 1,602
  • 1
  • 12
  • 31
  • Can you please fix the capitalization of class `String` in your answer. Also, `String x = "**";` and String `x = new String("**");` are not **exactly** the same things, since they can produce different memory allocation. – PM 77-1 Oct 31 '13 at 02:12
  • @PM77-1 No problem, I've been in .NET world too long, which doesn't care about string vs String. Your right about allocation, but I'm worried more about layman's terms than technically correct. – Resorath Oct 31 '13 at 02:17
  • 1
    @Skippy - They are all good answers (including this one). You just need to understand the difference between the object itself and a reference to this object. `null` is often used to signify that the object either has not been created yet or is no longer needed and should be available for garbage collection. – PM 77-1 Oct 31 '13 at 02:27
  • I downvoted this. "... You are saying that there is an object ... which isn't referencing anything ..." - NOT TRUE. You are saying that there is no object at all. – Dawood ibn Kareem Oct 31 '13 at 02:31
  • @DavidWallace Your right, I changed the wording to reference instead of object. – Resorath Oct 31 '13 at 02:33
  • 1
    @Skippy, I think the two best answers here were posted by Adrian Shum and Hot Licks. Nothing really to choose between them. I guess Adrian's diagrams give him the edge. But what matters is what YOU found helpful - you asked the question, not I. – Dawood ibn Kareem Oct 31 '13 at 02:44
4

String str is a reference to an object. That is, it's not an actual object, but a variable which can contain the address of an object. When you assign a value to str you are changing the address stored within and changing which object it addresses.

null is reference value which points to no object. It's about as close to nothing as you can get. If you assign null to a String reference (String str = null;), you cannot then invoke any method of String using that reference -- all attempts will result in NullPointerException.

"" is a character String which contains no characters -- zero length. It is still an object, though, and if you assign its address to your String reference variable (String str = "";) you can then take its length, compare it to another String, extract its hashCode, etc.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • Sometimes you want to indicate that there's nothing at all. Or you may initialize reference X to `null` and then execute a complex algorithm that is supposed assign a valid value to X. If the valid value never gets assigned you can detect that since X will be null. – Hot Licks Oct 31 '13 at 02:15
3

Practically speaking, null means "not available for calling methods". If an object is allowed to be null, you must always check it for null before calling method on it.

An attempt to call any method on a null object is unconditionally an error. In nearly all cases it's a programming error, too, because you are supposed to either

  • Ensure that a variable is always non-null, or
  • Check a variable that could legally be null before calling methods on it.

On the other hand, an empty object lets you call methods. For example, you can find the length of an empty string - it is zero. You could also iterate a string, pass it to methods that expect non-null strings, and so on.

To visualize this, consider a Boolean object instead of a String. Unlike the primitive boolean that has only two states, namely true ("yes") and false ("no"), the Boolean object has three states:

  • Yes
  • No
  • Don't know

This third "don't know" state corresponds to null. It's neither true nor false state. Your program can use this third state to its advantage - for example, you can use comparison to null to see if a value has been set, or set a value to null to "unset" its value.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

In Java null and an empty String are two different things.

If an String is null then you can not access its methods as it will throw a NullPointerException, however if a String is "" then the String object is valid and you can access its methods.

For example

 String a = null;
 String b = "";

 System.out.println (a.length());   // No Good
 System.out.println (b.length());   // Prints 0
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
2

Conceptually null is a special value which means that the variable points to an invalid object, so it doesn't refer to anything valid in the sense that you can't access its content (variables or methods).

You can see it as a sort of special condition which has been added to languages because it was useful to be able to have pointers that refer to nothing. But there is some discordance here, in fact some languages prevent the necessity of a null value by forcing you to have just inizialized (meaningful) values.

There is difference in your example, "" is a valid object: it's an empty string while null is not a valid object.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • @DavidWallace: that is. The variables doesn't refer to a valid object, or refer to an invalid one, you can see it both ways. The concept of "doesn't refer to anything" is just the meaning you give to the `null` value itself, it doesn't mean absolutely anything since it refers to something, which is the `null` value itself. That is `null` is just a value and it stands for an uninitialised or undefined object, which is inherently invalid. – Jack Oct 31 '13 at 03:09
  • No. A null variable does NOT refer to an invalid object. It does not refer to an uninitialised object. It does not refer to an undefined object. A null variable DOES NOT REFER TO ANY OBJECT AT ALL, valid or invalid, initialised or uninitialised, defined or undefined. By referring to an object "pointing to" something, your answer confuses the concept of a variable, with the concept of an object; which are precisely the concepts that the OP most needs to get straight, in order to understand this stuff. – Dawood ibn Kareem Oct 31 '13 at 03:57
  • @DavidWallace: "the pointer points to an invalid object" was indeed a typo which I fixed. But your CAPS part is wrong: a variable set to `null` refer to a specific value which is `null`. This is the common problem with `null` values that I was trying to point out in my answer. `null` is a value of a special type, it isn't an object (`null instanceof Object == false`) but at the same time it is (assigning `null` to any object variable is valid). It is confusing just because it is, ignorance is worse than confusion. The JSL specifically states this confusion: – Jack Oct 31 '13 at 04:18
  • @DavidWallace: From JSL 4.1: There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always undergo a widening reference conversion to any reference type. – Jack Oct 31 '13 at 04:18
2

Let's compare this to Python. In Python, the equivalent to null is None.

>>> test = ""
>>> test1 = None

This is setting an empty string and a "null" string.

>>> test
''
>>> test1
None

In Python we can test nullity using is

>>> test is None
False
>>> test1 is None
True

We can test for empty strings using ==

>>> test == ""
True
>>> test1 == ""
False

null (like None) is the absence of a value.

Andy
  • 49,085
  • 60
  • 166
  • 233
2

Although many object-oriented frameworks implement references with pointers, it is better to think of references not as "pointing to" objects, but rather as "identifying" them [personally, I like the term "object identifier" to describe references, since the term "reference" is somewhat overloaded in different contexts]. Although object identifiers are not human readable, one can imagine the system as giving each object an associated number starting at 1, and each class-type variable as either having an object number or a zero written on it. Since class-type variables and array slots default to holding zero, and there will never be a zeroth object, there's no danger that the default-valued variable of an uninitialized variable or array slot will identify a valid object.

supercat
  • 77,689
  • 9
  • 166
  • 211
0

I prefer using the concept of containers/boxes to understand this concept

Let's start with this

String thing = "";

Imagine you have a container/box where you can store any value as long as you put the value between double quote marks "", if you decide to just put the double quotation mark without a value inside the box there is absolutely nothing wrong with that and any time you open your box you still see something inside (The double quotation mark )

Now This big man over here called null

String thing = null;

In simple terms look at null as being absolutely nothing

What does all this mean? When you open the first box you see the double quotation ""

When you open the second box you see nothing (it's just an empty box)

Olayiwola Osho
  • 121
  • 2
  • 4