🌐
W3Schools
w3schools.com › sql › sql_null_values.asp
SQL NULL Values - IS NULL and IS NOT NULL
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL; Try it Yourself » ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected] · If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected] · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
W3Schools
w3schools.io › java › java14-nullpointer-exception
java14 NullPointerException improvement new features Latest java features tutorials with examples - w3schools
NullPointerException is thrown by the calling method or accessing property on a null object. Java 14 introduced an improvement to a user in how the error message is displayed.
🌐
W3schools
w3schools.tech › tutorial › java › java_nullpointerexception
Java - Null Pointer Exception: A Beginner's Guide - Advanced Java - W3schools
Hello there, future Java developers! Today, we're going to embark on an exciting journey into the world of Java programming, specifically focusing on one of the most common exceptions you'll encounter: the Null Pointer Exception. Don't worry if you're completely new to programming – I'll ...
🌐
W3Schools
w3schools.com › java › java_ref_keywords.asp
Java Keywords
Java has a set of keywords that are reserved words that cannot be used as variables, methods, classes, or any other identifiers: Note: true, false, and null are not keywords, but they are literals and reserved words that cannot be used as identifiers. ... If you want to use W3Schools services ...
🌐
W3Schools
w3schools.com › c › c_null.php
C NULL
Tip: Always check if a pointer is NULL before using it. This helps avoid crashes caused by accessing invalid memory. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected] · If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected] · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
W3Schools
w3schools.in › java › keywords
Java Keywords - W3Schools
You can't use keyword as identifier in your Java programs, its reserved words in Java library and used to perform an internal operation. true, false and null are not reserved words but cannot be used as identifiers, because it is literals of built-in types.
🌐
W3Schools
w3schools.com › sql › sql_isnull.asp
W3Schools.com
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST · SQL HOME SQL Intro SQL Syntax SQL Select SQL Select Distinct SQL Where SQL Order By SQL And SQL Or SQL Not SQL Insert Into SQL Null ...
🌐
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 - When we write code, the reason why a reference points to null is often irrelevant. We just check for null and take appropriate actions. For example, suppose that we have to write a loop that sends emails for a list of persons. The code (in Java) could look like this:
🌐
Upwork
upwork.com › resources › articles › {name}
Null in Java: Understanding the Basics - Upwork
August 5, 2024 - This guide explains the concept, common pitfalls, and best practices for Java developers. ... What is null in Java? Is null an instance of anything? What's the difference between a null reference and a null value? And what exactly is going on under the hood with your memory management when you set a variable to null?
Find elsewhere
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.)

🌐
W3Schools
w3schools.com › java › java_data_types_non-prim.asp
Java Non-Primitive Data Types
Primitive types always hold a value, whereas non-primitive types can be null. Examples of non-primitive types are Strings, Arrays, Classes etc. You will learn more about these in a later chapter. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected] · If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected] · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
DataCamp
datacamp.com › doc › java › null
null Keyword in Java: Usage & Examples
Learn about the `null` keyword in Java, its usage, syntax, and best practices to avoid `NullPointerException` with practical examples.
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
Tip: For a list of all errors and exception types, go to our Java Errors and Exception Types Reference. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
🌐
GeeksforGeeks
geeksforgeeks.org › java › interesting-facts-about-null-in-java
Interesting facts about null in Java - GeeksforGeeks
September 3, 2024 - An empty string is a string that contains no characters, while an empty array is an array that contains no elements. The Java programming language has a built-in null type, called "null", which is a subtype of all reference types.
🌐
W3Schools
w3schools.com › java › ref_keyword_void.asp
Java void Keyword
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
🌐
W3Schools
w3schoolsua.github.io › sql › sql_null_values_en.html
SQL NULL Values. Examples. Lessons for beginners. W3Schools in English
SQL NULL Values. What is a NULL Value? How to Test for NULL Values? To use the IS NULL and IS NOT NULL. Demo Database. The IS NULL Operator. The IS NOT NULL Operator. Always use IS NULL to look for NULL values. Examples. Video Lesson. Lessons for beginners. W3Schools in English
🌐
Baeldung
baeldung.com › home › java › what is the null type in java?
What Is the null Type in Java? | Baeldung
January 8, 2024 - 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.
🌐
W3Schools
w3schools.com › java › java_syntax.asp
Java Syntax
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
Top answer
1 of 12
77
It's an old solution to a problem that happened way before Java. I'm old, but I still use it because it's memory efficient and fast. Situational example.. You have a function that returns an int. If you know its always supposed to be positive, it's pretty common to return -1 to communicate that something went wrong, is absent, isn't finished doing something, etc. It's quick. Only requires a single 32/64 bit piece of memory. Solid choice to use when documented well. Instead of integer, let's say you have a class that hypothetically takes up 200 bytes of memory. I don't want to just stop my program because something isn't in a list, and I can't just return -1. I could create a default class that represents a problem just like "-1" does, but that's going to allocate 200 bytes. Assigning the variable to 'null' doesn't allocate 200 bytes. It just points to a universal 'null' memory address that is well understood by the JVM to mean "nothing." "Nothing" saves space and saves a lot of computation power from .equals(...) and even garbage collection. Is it worth having to rely on performing a null check constantly? Actually, yes. It is usually worth it. If people are used to dealing with null, it's not a problem. Coming from different languages where null is not allowed, you get a lot of NullPointerExceptions. Skill issue, though. Edit: Removed most mentions of exceptions to focus on why a new programmer might see "return null" and to appease the Spring devs who believe checked exceptions are relative to OPs question.
2 of 12
6
In some functions, if you can't find the value you want to return, you might return null instead. For example, imagine you have a method that is meant to search for an object in a collection that fits certain criteria. If your collection does not contain such an object, then your method might handle that by returning null. Generally though, this would not be considered great software design. It is very easy to run into runtime errors this way, for example, if a developer using such a method does not realize that it could return null.
🌐
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)".