Definition. Null

[comp1110-2R]

In Java, null is a special value that can be used as an instance of any reference type. It is also the default value of any reference type. That is, when you create an array of a reference type without giving the specific values in it, for example using new String[10], the array will initially be filled with null.

Besides being a default value, null may be used intentionally to mark the optional absence of values. More modern language often use special option types for this, and either disallow null entirely or require a special marker on a type to make it "nullable". This is because when null can be anywhere, it is usually the cause of many bugs. Tony Hoare called the invention of null his "billion-dollar mistake".

The thing about null is that while you can assign it to any variable of a reference type or return it from any method that needs to return something of a reference type, you cannot use it in any interesting way without causing a NullPointerException. The only things that are safe to do are assignments of it, passing it as an argument (this may cause a bug further down the line) and comparisons using the == operator. In particular, if null has been assigned to a variable x, any use of the "dot" operator to access a field or method of x will cause an exception.

bars magnifying-glass caret-down plus minus arrow-right xmark