What is null?


  1. null is it an instance of something?
  2. What type does null belong to?
  3. What is null?
  4. How is it represented in memory?

Free translation of the question "What is null in Java?" from the participant @unj2.

Author: Suvitruf - Andrei Apanasik, 2018-08-20

1 answers

null is it an instance of something?

There is no such type that corresponds to instanceof from null.

15.20.2 Type Comparison Operator instanceof

RelationalExpression:
  RelationalExpression instanceof ReferenceType

In runtime, the result of the operator instanceof will be true if the value of RelationalExpression is not null and the reference can be cast to ReferenceType without getting an exception ClassCastException. Otherwise, the result will be false.

This means that for any type of E and R, for any E o, where o == null, o instanceof R it will always be false.

What type does null belong to?

JLS 4.1 The Kinds of Types and Values.

There is also a special type - null, the type of the expression null, which has no name. And because the type null has no name, you cannot declare variable to be of type null{[76] or cast the variable to the type null. null the link is the only possible value of an expression of type null . null can always be cast to any reference type. In reality, you can ignore the null type and pretend that null is just a special literal that can be any reference type.

What is null?

As stated in the JLS quote above, we can assume that "null is just a special literal that can be any reference type".

In Java null == null (which is not true for all languages). From the description java.lang.Object:

public boolean equals(Object obj)

For any non - null variable x, x.equals(null) must return false.

null it is also the default value for all reference types.

JLS 4.12.5 Initial Values of Variables:

  • Static class variables, instance variables, and arrays are initialized to the default value when created: * For all reference types (§4.3), the default value is - null.

You can use this property for deferred initialization, where the field will have the initial value null until it is actually used, where it will be replaced by a "real" value (which can be expensive to calculate).

There are other uses. If you look at java.lang.System:

public static Console console()

Returns: The system console, if any, otherwise null.

This is a very common practice: null is used to refer to a non-existent object.

Another example - java.io.BufferedReader:

public String readLine() throws IOException

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.

readLine() it will return instanceof String for each row until it gets null denoting the end. This allows you to process each row as follows way:

String line;
while ((line = reader.readLine()) != null) {
   process(line);
}

Note: an empty string is not a problem, because "" != null.

Let's consider java.util.Map<K,V>:

V get(Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Here we see that using null can complicate things. It says that if there is no such key, null will be returned. The second statement states that even if there is an element for such a key, it can still return null.

For example, java.util.Hashtable makes things easier by disallowing null in keys and values; so if V get(Object key) returns null it is clearly indicates that there is nothing under such a key.

Automatic unboxing operations on null will throw java.lang.NullPointerException:

Integer i = null;
     
// при анбоксинге null в integer будет выброшен NullPointerException 
int a = i;

To summarize, null is used as a special meaning to denote:

  • No initialized state.
  • Terminal condition
  • A non-existent object.
  • Unknown value.

How is null represented in memory?

From specification JVM:

The Java Virtual Machine specification does not mandate a concrete value encoding null.

Small addition

Interesting quote C. A. R Hoare:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

You can also view the presentation about the billion-dollar error.

When the answer was formed using the answer to the question "What is null in Java?" from the participant @polygenelubricants.

 53
Author: Suvitruf - Andrei Apanasik, 2020-07-19 13:45:31