Comparing the generated bytecodes is mostly meaningless, since most of the optimization happens in run time with the JIT compiler. I'm going to guess that in this case, either expression is equally fast. If there's any difference, it's negligible.

This is not something that you need to worry about. Look for big picture optimizations.

Answer from polygenelubricants on Stack Overflow
🌐
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.
🌐
Quora
quora.com › Why-do-we-use-null-instead-of-NULL-in-Java
Why do we use null instead of NULL in Java? - Quora
First I’d take the liberty to modify your question. In Java class names generally starts with capital letters. So, if null was a class (which it is not) it could have been “Null”. NULL is not any option.
🌐
openHAB Community
community.openhab.org › setup, configuration and use › scripts & rules
Is there a difference between null and NULL? - Scripts & Rules - openHAB Community
July 8, 2018 - Working with a lot of hash maps in my rules I have a lot of If statements that filter items states that contains a null (!== null). As I’m not an expert in Java I was wondering if there is a difference between null and NULL and in which use-case I need to check whether a “null” or a “NUL...
🌐
Reddit
reddit.com › r/javahelp › different between null != variable vs variable!=null
r/javahelp on Reddit: Different between null != variable vs variable!=null
September 9, 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)
🌐
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 - In Java, there is a literal named null. You can assign null to any variable that has an Object type, but the reference the variable points to is not an instance of an Object.
🌐
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)".
Find elsewhere
🌐
Quora
quora.com › What-is-a-better-syntax-in-Java-obj-null-or-null-obj-when-checking-if-an-object-exists
What is a better syntax in Java: 'obj == null' or 'null == obj', when checking if an object exists? - Quora
Answer (1 of 7): I read everywhere responses like —picking randomly Lew Bloch answer : « variable == null reads naturally. The reverse does not. » and conclude. Yes, for most indo-european speaking language. You learn and formulate your thinking on your mother language as child.
🌐
Reddit
reddit.com › r/java › java and nulls
r/java on Reddit: Java and nulls
August 24, 2024 -

It appears the concept of nulls came from Tony Hoare back in 1965 when he was working on Algol W. He called it his "billion dollar mistake". I was wondering if James Gosling has ever expressed any thoughts about wether or not adding nulls to Java was a good or bad thing?

Personally, coming to Java from Scala and Haskell, nulls seem like a very bad idea, to me.

I am considering making an argument to my company's engineering team to switch from using nulls to using `Optional` instead. I am already quite aware of the type system, code quality, and coding speed arguments. But I am very open to hearing any arguments for or against.

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

🌐
DEV Community
dev.to › dj_devjournal › understanding-null-in-java-4o31
Understanding null in Java - DEV Community
October 16, 2019 - The output of the above code snippet is shown in Figure 1 shown below. Figure 1: OUTPUT of the code snippet written above. In Java, null is a reserved word (keyword) for literal values.
🌐
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.
🌐
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 Java Virtual Machine specification does not mandate a concrete value encoding null. ... If a reference points to null, it simply means that there is no value associated with it.
🌐
Baeldung
baeldung.com › home › java › avoid check for null statement in java
Avoid Check for Null Statement in Java | Baeldung
April 8, 2019 - A quick and practical guide to null-safety annotations in Spring. ... According to the Javadoc for NullPointerException, it’s thrown when an application attempts to use null in a case where an object is required, such as:
🌐
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.
🌐
Coderanch
coderanch.com › t › 496486 › java › null-null-java
null and not null in java (Beginning Java forum at Coderanch)
Beware of looking in databases, where one uses three-value logic and NULL may be interpreted "don't know", so 123 < NULL, 123 > NULL and 123 = NULL always return NULL. SQL is different from Java, and NULL in SQL may mean something completely different from null in Java.
🌐
JoeHx Blog
joehxblog.com › does-null-equal-null-in-java
Does Null Equal Null in Java? – JoeHx Blog
October 31, 2018 - true: true false: false null == null: true string == null: true number == null: true Objects.equals(null, null): true Objects.equals(string, null): true Objects.equals(number, null): true Objects.equals(string, number): true · The first two outputted lines were just to get a feel as to how Java outputs the raw boolean values true and false. Everything here pretty much is as expected; the only lines that I find interesting is the output I commented out: