This was intended as a meme but is actually a good representation of what "Null" is. In C#, when you declare string s = "My shit"; it means that "s" is a reference to a memory location that holds the data "My shit". string s = null; means that the reference "s" exists but it's not pointing to any object, as in it holds nothing. Answer from abd53 on reddit.com
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
The null keyword in Java is a literal that represents a null reference, one that points to no object. It is often used to indicate that a reference variable does not currently refer to any object or that a method has no return value.
Discussions

Best way to handle nulls in Java? - Software Engineering Stack Exchange
Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness. ... 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 ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
February 23, 2011
java - What does is mean by null pointing to nothing and why use null at all? - Stack Overflow
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 be... More on stackoverflow.com
🌐 stackoverflow.com
Acknowledging that null is a problem
What solution do you propose? Remember: you have to support old code, too. More on reddit.com
🌐 r/java
294
112
June 12, 2021
Why we return null on java?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
37
25
August 20, 2024
Top answer
1 of 14
331

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

🌐
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.
🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - Java's creators included null to provide a standard way to represent the absence of a value in object-oriented programming. The intention was to give developers a straightforward mechanism to check if an object reference was pointing to any valid memory location before accessing it. Null was meant to simplify error checking and improve code robustness by clearly indicating uninitialized or absent values.
🌐
Coderanch
coderanch.com › t › 688734 › java › null
what does null mean? (Beginning Java forum at Coderanch)
December 24, 2017 - Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor) ... Yep, null means it does not have any value whatsoever - not even zero or an empty String.
🌐
MojoAuth
mojoauth.com › special-characters › null-0-in-java
Null (\0) in Java | Understanding Special Characters in Programming
The null character \0 in Java is treated as a regular character that can be included in strings. It is commonly used to represent a terminating character in various programming scenarios, especially when dealing with byte streams or raw data.
Find elsewhere
🌐
Logit
logit.io › blog › post › null-in-java
The Concept Of Null In Java
February 4, 2025 - Null is a reserved word (keyword) in Java for literal values. It is a literal similar to the true and false. In Java, null is a keyword much like the other keywords public, static or final.
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.

🌐
Quora
quora.com › Why-is-null-considered-a-special-value-in-most-languages-such-as-Java-Is-it-better-for-no-object-to-be-considered-empty-instead
Why is 'null' considered a special value in most languages, such as Java? Is it better for no object to be considered 'empty' instead? - Quora
Answer: The null is related to pointers. If the pointer points nowhere, it contains the null value. In languages like Java, the “object identifiers” are actually wrapped pointers to the objects.
🌐
Codemia
codemia.io › knowledge-hub › path › what_is_null_in_java
What is null in Java?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
Medium
donraab.medium.com › what-if-null-was-an-object-in-java-3f1974954be2
What if null was an Object in Java? | Medium
January 5, 2024 - The tricky part would be how to make null capable of representing any interface and class, and dispatching calls to a method named doesNotUnderstand for any methods from those interfaces that null wouldn’t understand. The Null class would have to behave like a Proxy for any type it is stored in, and forward methods sent to a class like Set, to a single method that could handle the “I’m not a Set” response appropriately. Perhaps with null as an Object in Java, it would be possible to do away with a whole variety of NullPointerExceptions.
🌐
TechCareer
techcareer.net › en › dictionary › null
What is Null? What does it do?
Null shows that an object or reference does not contain any data or does not point to an object. For instance, in languages like Java and C#, null is used to indicate that an object reference does not point to a valid object.
🌐
Oracle
docs.oracle.com › javaee › 7 › tutorial › bean-validation002.htm
21.2 Validating Null and Empty Strings - Java Platform, Enterprise Edition: The Java EE Tutorial (Release 7)
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all.
🌐
Sentry
sentry.io › sentry answers › java › what is a nullpointerexception, and how do i fix it?
What is a NullPointerException, and how do I fix it? | Sentry
May 15, 2023 - A NullPointerException in Java is one of the most common errors. It means that you are trying to access a part of something that doesn’t exist.
Top answer
1 of 9
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.

2 of 9
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.

🌐
Java Design Patterns
java-design-patterns.com › patterns › null-object
Null Object Pattern in Java: Streamlining Error Handling with Graceful Defaults | Java Design Patterns
... Null Object pattern handles "empty" objects gracefully. ... In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral ("null") behavior.
🌐
Ducmanhphan
ducmanhphan.github.io › 2020-02-01-Working-with-Nulls-in-Java
Working with Nulls in Java
February 1, 2020 - Best practice for Optional in Java. Null is a value that indicates that a reference does not refer to an object.
🌐
W3Schools
w3schools.com › sql › sql_null_values.asp
SQL NULL Values - IS NULL and IS NOT NULL
ADD ADD CONSTRAINT ALL ALTER ALTER COLUMN ALTER TABLE AND ANY AS ASC BACKUP DATABASE BETWEEN CASE CHECK COLUMN CONSTRAINT CREATE CREATE DATABASE CREATE INDEX CREATE OR REPLACE VIEW CREATE TABLE CREATE PROCEDURE CREATE UNIQUE INDEX CREATE VIEW DATABASE DEFAULT DELETE DESC DISTINCT DROP DROP COLUMN DROP CONSTRAINT DROP DATABASE DROP DEFAULT DROP INDEX DROP TABLE DROP VIEW EXEC EXISTS FOREIGN KEY FROM FULL OUTER JOIN GROUP BY HAVING IN INDEX INNER JOIN INSERT INTO INSERT INTO SELECT IS NULL IS NOT NULL JOIN LEFT JOIN LIKE LIMIT NOT NOT NULL OR ORDER BY OUTER JOIN PRIMARY KEY PROCEDURE RIGHT JOIN ROWNUM SELECT SELECT DISTINCT SELECT INTO SELECT TOP SET TABLE TOP TRUNCATE TABLE UNION UNION ALL UNIQUE UPDATE VALUES VIEW WHERE MySQL Functions
🌐
Spring
docs.spring.io › spring-framework › reference › core › null-safety.html
Null-safety :: Spring Framework
With arrays and varargs, you need to be able to differentiate the nullness of the elements from the nullness of the array itself. Pay attention to the syntax defined by the Java specification which may be initially surprising. For example, in @NullMarked code: @Nullable Object[] array means individual elements can be null but the array itself cannot.