Is null an instance of anything?

No, there is no type which null is an instanceof.

15.20.2 Type Comparison Operator instanceof

RelationalExpression:
    RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

This means that for any type E and R, for any E o, where o == null, o instanceof R is always false.


What set does 'null' belong to?

JLS 4.1 The Kinds of Types and Values

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 be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.


What is null?

As the JLS quote above says, in practice you can simply pretend that it's "merely a special literal that can be of any reference type".

In Java, null == null (this isn't always the case in other languages). Note also that by contract, it also has this special property (from java.lang.Object):

public boolean equals(Object obj)

For any non-null reference value x, x.equals(null) should return false.

It is also the default value (for variables that have them) for all reference types:

JLS 4.12.5 Initial Values of Variables

  • Each class variable, instance variable, or array component is initialized with a default value when it is created:
    • For all reference types, the default value is null.

How this is used varies. You can use it to enable what is called lazy initialization of fields, where a field would have its initial value of null until it's actually used, where it's replaced by the "real" value (which may be expensive to compute).

There are also other uses. Let's take a real example from java.lang.System:

public static Console console()

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

This is a very common use pattern: null is used to denote non-existence of an object.

Here's another usage example, this time from 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.

So here, readLine() would return instanceof String for each line, until it finally returns a null to signify the end. This allows you to process each line as follows:

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

One can design the API so that the termination condition doesn't depend on readLine() returning null, but one can see that this design has the benefit of making things concise. Note that there is no problem with empty lines, because an empty line "" != null.

Let's take another example, this time from 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 start to see how using null can complicate things. The first statement says that if the key isn't mapped, null is returned. The second statement says that even if the key is mapped, null can also be returned.

In contrast, java.util.Hashtable keeps things simpler by not permitting null keys and values; its V get(Object key), if returns null, unambiguously means that the key isn't mapped.

You can read through the rest of the APIs and find where and how null is used. Do keep in mind that they aren't always the best practice examples.

Generally speaking, null are used as a special value to signify:

  • Uninitialized state
  • Termination condition
  • Non-existing object
  • An unknown value

How is it represented in the memory?

In Java? None of your concern. And it's best kept that way.


Is null a good thing?

This is now borderline subjective. Some people say that null causes many programmer errors that could've been avoided. Some say that in a language that catches NullPointerException like Java, it's good to use it because you will fail-fast on programmer errors. Some people avoid null by using Null object pattern, etc.

This is a huge topic on its own, so it's best discussed as answer to another question.

I will end this with a quote from the inventor of null himself, C.A.R Hoare (of quicksort fame):

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.

The video of this presentation goes deeper; it's a recommended watch.

Answer from polygenelubricants on Stack Overflow
🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - Uninitialized variables for reference types default to null, which can be useful but also requires careful null checks to prevent errors. Memory management. Using null helps manage memory by allowing the garbage collector to reclaim memory once a reference is set to null. Best practices for handling null in Java 1.
Top answer
1 of 14
330

Is null an instance of anything?

No, there is no type which null is an instanceof.

15.20.2 Type Comparison Operator instanceof

RelationalExpression:
    RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

This means that for any type E and R, for any E o, where o == null, o instanceof R is always false.


What set does 'null' belong to?

JLS 4.1 The Kinds of Types and Values

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 be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.


What is null?

As the JLS quote above says, in practice you can simply pretend that it's "merely a special literal that can be of any reference type".

In Java, null == null (this isn't always the case in other languages). Note also that by contract, it also has this special property (from java.lang.Object):

public boolean equals(Object obj)

For any non-null reference value x, x.equals(null) should return false.

It is also the default value (for variables that have them) for all reference types:

JLS 4.12.5 Initial Values of Variables

  • Each class variable, instance variable, or array component is initialized with a default value when it is created:
    • For all reference types, the default value is null.

How this is used varies. You can use it to enable what is called lazy initialization of fields, where a field would have its initial value of null until it's actually used, where it's replaced by the "real" value (which may be expensive to compute).

There are also other uses. Let's take a real example from java.lang.System:

public static Console console()

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

This is a very common use pattern: null is used to denote non-existence of an object.

Here's another usage example, this time from 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.

So here, readLine() would return instanceof String for each line, until it finally returns a null to signify the end. This allows you to process each line as follows:

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

One can design the API so that the termination condition doesn't depend on readLine() returning null, but one can see that this design has the benefit of making things concise. Note that there is no problem with empty lines, because an empty line "" != null.

Let's take another example, this time from 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 start to see how using null can complicate things. The first statement says that if the key isn't mapped, null is returned. The second statement says that even if the key is mapped, null can also be returned.

In contrast, java.util.Hashtable keeps things simpler by not permitting null keys and values; its V get(Object key), if returns null, unambiguously means that the key isn't mapped.

You can read through the rest of the APIs and find where and how null is used. Do keep in mind that they aren't always the best practice examples.

Generally speaking, null are used as a special value to signify:

  • Uninitialized state
  • Termination condition
  • Non-existing object
  • An unknown value

How is it represented in the memory?

In Java? None of your concern. And it's best kept that way.


Is null a good thing?

This is now borderline subjective. Some people say that null causes many programmer errors that could've been avoided. Some say that in a language that catches NullPointerException like Java, it's good to use it because you will fail-fast on programmer errors. Some people avoid null by using Null object pattern, etc.

This is a huge topic on its own, so it's best discussed as answer to another question.

I will end this with a quote from the inventor of null himself, C.A.R Hoare (of quicksort fame):

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.

The video of this presentation goes deeper; it's a recommended watch.

2 of 14
33

Is null an instance of anything?

No. That is why null instanceof X will return false for all classes X. (Don't be fooled by the fact that you can assign null to a variable whose type is an object type. Strictly speaking, the assignment involves an implicit type conversion; see below.)

What set does 'null' belong to?

It is the one and only member of the null type, where the null type is defined as follows:

"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 be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type." JLS 4.1

What is null?

See above. In some contexts, null is used to denote "no object" or "unknown" or "unavailable", but these meanings are application specific.

How is it represented in the memory?

That is implementation specific, and you won't be able to see the representation of null in a pure Java program. (But null is represented as a zero machine address / pointer in most if not all Java implementations.)

🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
Optional Class: Consider using the Optional class introduced in Java 8 to handle nullable values more gracefully. Optional<String> optionalStr = Optional.ofNullable(str); optionalStr.ifPresent(System.out::println); Avoid Overuse: While null can be useful, overusing it can lead to code that is harder to read and maintain.
🌐
Logit
logit.io › blog › post › null-in-java
The Concept Of Null In Java
February 4, 2025 - You have to deal with the Optional even in cases when you’re sure that the value is there. ... Therefore, use direct references for fields and carefully analyse whether a field can be null or not at any given point. If your class is well-encapsulated, this should be fairly easy. Java bytecode, which is the instruction set for the Java Virtual Machine (JVM), has specific operations to handle 'null' values efficiently.
🌐
freeCodeCamp
freecodecamp.org › news › a-quick-and-thorough-guide-to-null-what-it-is-and-how-you-should-use-it-d170cea62840
A quick and thorough guide to ‘null’: what it is, and how you should use it
June 12, 2018 - The value 0 (all bits at zero) is a typical value used in memory to denote null. It means that there is no value associated with name. You can also think of it as the absence of data or simply no data.
Top answer
1 of 11
47

If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.

2 of 11
22

Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}

If each of these may or may not return a successful value, you can change the APIs to Optionals:

String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/


@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.


Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.


Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.

🌐
Baeldung
baeldung.com › home › java › what is the null type in java?
What Is the null Type in Java? | Baeldung
January 8, 2024 - Because of polymorphism in Java, we can call these methods like this: ... The compiler will understand what method we’re referencing. But the following statement will cause a compiler error: ... Why? Because null can be cast to both String and Integer – the compiler won’t know which method to choose. As we’ve seen already, we can assign the null reference to a variable of a reference type even though null is technically a different, separate type. If we try to use some property of that variable as if it wasn’t null, we’ll get a runtime exception – NullPointerException.
🌐
YouTube
youtube.com › watch
Java Null Keyword - How To Use Null in Java #44 - YouTube
$1,000 OFF ANY Springboard Tech Bootcamps with my code ALEXLEE. See if you qualify for the JOB GUARANTEE! 👉 https://bit.ly/3HX970hThe java null keyword lets...
Published   July 9, 2020
Find elsewhere
🌐
Javatpoint
javatpoint.com › null-keyword-in-java
Java null reserved word - Javatpoint
In Java, null is a reserved word for literal values. It seems like a keyword, but actually, it is a literal similar to true and false. - Learn basics of Java null reserved word
🌐
GeeksforGeeks
geeksforgeeks.org › java › interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - The Java programming language has a built-in null type, called "null", which is a subtype of all reference types. However, it cannot be used as a type for a variable, because it doesn't have any instance and cannot be instantiated. It is considered a best practice to check for null values before performing any operations on them, to avoid the risk of a NullPointerException (NPE).
🌐
DEV Community
dev.to › dj_devjournal › understanding-null-in-java-4o31
Understanding null in Java - DEV Community
October 16, 2019 - That’s about null in Java. Common scenarios around the null have been tried to cover: how to use it, where to use it, and how it can be used as the placeholder for reference type variables.
🌐
Medium
medium.com › @dilhan9g › understanding-null-in-java-what-it-is-and-when-to-use-it-4a87dabb5f36
Understanding null in Java: What It Is and When to Use It | by Suresh Dilhan | Medium
May 19, 2025 - Use null to represent missing or optional data in reference types. Avoid null for primitives-use wrapper classes if you need nullability. Minimize the use of null by using alternatives like the Optional class (introduced in Java 8) for return ...
🌐
DataFlair
data-flair.training › blogs › java-null
Java Null - 7 Unknown Facts about Null in Java - DataFlair
May 2, 2024 - You can use == and != comparisons with null types in Java. When the program tries to access a part of the memory which is not initialized by default, then the compiler throws a null pointer exception.
🌐
Scaler
scaler.com › topics › java-null
What is Java Null? - Scaler Topics
December 14, 2022 - The equality (==) and inequality (!=) operators can be used with null in Java, allowing for null checks on objects. ... Null was created to provide a way to point to the absence of something. When you declare a variable in Java, you must assign the type it expects to store in that variable.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
January 8, 2024 - But that is rarely applicable in real-world applications. Now let’s suppose that we’re working with an API that cannot accept null parameters or can return a null response that has to be handled by the client. This presents the need for us to check the parameters or the response for a null value. Here, we can use Java Assertions instead of the traditional null check conditional statement:
🌐
Coderanch
coderanch.com › t › 523760 › java › null-null-java
null==something vs something==null in java (Beginning Java forum at Coderanch)
But that's only because that's faster than the alternative: var != null && var.equals("value"). Edit: I should of course use the same constant value... SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Rob Prime wrote:. . . that's faster than the alternative: var != null && var.equals("value"). . . . that means "faster to write", I presume? I would have thought any difference in execution speed would be so small as to be undetectable.
🌐
Mezo Code
mezocode.com › home › handling null in java: 10 pro strategies for expert developers
Handling Null in Java: 10 Pro Strategies for Expert Developers | Mezo Code
October 16, 2024 - When to use: Optional is best used as a return type where there might not be a value to return, and when you want to avoid null checks. Java 8 introduced the Optional class, which can help you express a variable that might be null more explicitly:
🌐
Java Design Patterns
java-design-patterns.com › patterns › null-object
Null Object Pattern in Java: Streamlining Error Handling with Graceful Defaults | Java Design Patterns
When you need to provide a default behavior in place of a null object. To simplify the client code by eliminating null checks. When a default action is preferable to handling a null reference. Commonly used in logging systems, the Null object helps prevent NullPointerExceptions, making it a ...