The dilemma

If a variable with null value gets used in your program causing a NullPointerException, this is clearly a situation in your program which you did not expect. You must ask yourself the question: "Did I not expect it because I didn't take into consideration the possibility of a null value or did I assume the value could never be null here?"

If the answer is the latter, the problem isn't because you didn't handle the null value. The problem happened earlier, and you're only seeing the consequence of that error on the particular line it's used. In this case, simply adding a if (variable != null) isn't going to cut it. You'll wind up skipping lines you were supposed to execute because the variable was null, and you'll ultimately hit a line further on where you again assumed it wouldn't be null.

When null should be used

As a general rule, return null only when "absent" is a possible return value. In other words, your data layer may search for a record with a specific id. If that record isn't found, you can either throw an exception or simply return null. You may do either, but I prefer not to throw exceptions in situations where the strong possibility exists. So you return null instead of a value.

The caller of this method, presumably written by you, knows the possibility exists that the record may not exist and checks for null accordingly. There is nothing wrong with this in this case, though you should handle this possibility as soon as possible as otherwise everywhere in your program you will need to deal with the possibility of a null value.

Conclusion

In other words, treat null as a legitimate value, but deal with it immediately rather than wait. Ideally in your program, you should ever only have to check if it is null once in your program and only in the place where such a null value is handled.

For every value you expect to be non-null, you need not add a check. If it is null, accept that there is an error in your program when it was instantiated. In essence, favor fail fast over fail safe.

Answer from Neil on Stack Exchange
Top answer
1 of 3
5

The dilemma

If a variable with null value gets used in your program causing a NullPointerException, this is clearly a situation in your program which you did not expect. You must ask yourself the question: "Did I not expect it because I didn't take into consideration the possibility of a null value or did I assume the value could never be null here?"

If the answer is the latter, the problem isn't because you didn't handle the null value. The problem happened earlier, and you're only seeing the consequence of that error on the particular line it's used. In this case, simply adding a if (variable != null) isn't going to cut it. You'll wind up skipping lines you were supposed to execute because the variable was null, and you'll ultimately hit a line further on where you again assumed it wouldn't be null.

When null should be used

As a general rule, return null only when "absent" is a possible return value. In other words, your data layer may search for a record with a specific id. If that record isn't found, you can either throw an exception or simply return null. You may do either, but I prefer not to throw exceptions in situations where the strong possibility exists. So you return null instead of a value.

The caller of this method, presumably written by you, knows the possibility exists that the record may not exist and checks for null accordingly. There is nothing wrong with this in this case, though you should handle this possibility as soon as possible as otherwise everywhere in your program you will need to deal with the possibility of a null value.

Conclusion

In other words, treat null as a legitimate value, but deal with it immediately rather than wait. Ideally in your program, you should ever only have to check if it is null once in your program and only in the place where such a null value is handled.

For every value you expect to be non-null, you need not add a check. If it is null, accept that there is an error in your program when it was instantiated. In essence, favor fail fast over fail safe.

2 of 3
8

Deciding whether or not null is a allowed as an object value is a decision that you must make consciously for your project.

You don't have to accept a language construct just because it exists; in fact, it is often better to enforce a strict rule against any nullvalues in the entire project. If you do this, you don't need checks; if a NullPointerException ever happens, that automatically means that there is a defect in your code, and it doesn't matter whether this is signalled by a NPE or by some other sanity check mechanism.

If you can't do this, for instance because you have to interoperate with other libraries that allow null, then you do have to check for it. Even then it makes sense to keep the areas of code where null is possible small if possible. The larger the project, the more sense it makes to define an entire "anti-corruption layer" with the only purpose of preserving stricter value guarantees than is possible elsewhere.

๐ŸŒ
Upwork
upwork.com โ€บ resources โ€บ articles โ€บ {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - We'll get to that later in this ... and how to avoid problems. In Java, null is a literal, a special constant you can point to whenever you wish to point to the absence of a value....
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.)

๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 750953 โ€บ java โ€บ difference-btw-null-var-var
What is the difference btw ; null != var and var != null (Beginning Java forum at Coderanch)
Mathematically speaking, the "==" and "!=" operators are commutative. Which means that by definition you can swap sides safely. Generally I prefer to compare "x == null" as it reads more easily in English, but the Java compiler and runtime don't care. On the other hand, a popular construct is "if "foo".equals(x)".
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
January 8, 2024 - If the client code calls this method without checking the argument for null, FindBugs would generate a warning at compile time. Developers generally rely on IDEs for writing Java code. And features such as smart code completion and useful warnings, for example when a variable may not have been assigned, certainly help a lot. Some IDEs also allow developers to manage API contracts and thereby eliminate the need for a static code analysis tool. IntelliJ IDEA provides the @NonNull and @Nullable annotations.
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ different between null != variable vs variable!=null
r/javahelp on Reddit: Different between null != variable vs variable!=null
November 25, 2023 -

Hi Java Guru

I have see some code where it uses null != vs variable!=null. Can someone please to which should I used in what situation and what sufficient does using one over the other one makes?

Thank you

Top answer
1 of 5
1
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 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. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar 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: 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.
2 of 5
1
Are you asking about null != variable vs variable != null? There is no difference in what gets executed, but the first variant makes it impossible to misstype it into a valid assignment and thus preferred by some. (and the misstake is something more resonable to be a problem in less strictly typed languages)
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - It is used to indicate that a variable or object does not currently have a value assigned to it. The null value is not the same as an empty string or an empty array. An empty string is a string that contains no characters, while an empty array ...
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 470680 โ€บ java โ€บ null-obj-obj-null
null != obj vs. obj != null (Beginning Java forum at Coderanch)
So if you want to produce code that appeals to the largest number of programmer, use (obj != null). There is a situation in Java where the common usage isn't always preferred and that's for this, str.equals("literal") Instead this is often used, "literal".equals(str) But there's a good reason for this and this is that the latter avoids a Null Pointer Exception if str is null.
๐ŸŒ
Reddit
reddit.com โ€บ r/programming โ€บ handling and avoiding "!=null" statements in java
r/programming on Reddit: Handling and avoiding "!=null" Statements in Java
June 13, 2013 - If, during object creation, one of the fields is null that shouldn't be, that should have been a type error: you shouldn't be able to create a Car without an Engine (unless that somehow makes sense in your domain). The second problem is that is less expressive. Think of Java's Collections' get: it returns the result, or null, but if you do map.insert(1,null), map.get(1), you get null: it's indistinguishable from a missing value, while the proper response would be an Option<T>, so you know whether the value was missing or just null.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 523760 โ€บ java โ€บ null-null-java
null==something vs something==null in java (Beginning Java forum at Coderanch)
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.
๐ŸŒ
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
๐ŸŒ
DataCamp
datacamp.com โ€บ doc โ€บ java โ€บ null
null Keyword in Java: Usage & Examples
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The null keyword in Java is a literal that represents a null reference, one that points to no object.
๐ŸŒ
DataFlair
data-flair.training โ€บ blogs โ€บ java-null
Java Null - 7 Unknown Facts about Null in Java - DataFlair
May 2, 2024 - Any data value which is not present in memory or set to null explicitly will return a Null Pointer Exception if accessed. A primary example of this would be trying to access an index in the array which is out of bounds. Let us see this with an example. ... package com.dataflair.javanull; import java.util.*; public class Main { public static String nullreturnfunc() { return null; } public static void main (String[] args) { String test; test=nullreturnfunc(); System.out.println(test.charAt(3)); } }
๐ŸŒ
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.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 688734 โ€บ java โ€บ null
what does null mean? (Beginning Java forum at Coderanch)
I can't always remember when to ... objects that just have the same value as one another. ... From my understanding of null, it means the variable has no value....
๐ŸŒ
Quora
quora.com โ€บ Why-is-null-null-true-in-java
Why is null == null true in java? - Quora
Answer (1 of 8): In java only references can have the value null. As per the Java Language Specification it's "merely a special literal that can be of any reference type". For references == returns true if and only if the value of the two references are the same (or informally "they point to the...