What is null in Java?

JavaNullTerminology

Java Problem Overview


What is null?

Is null an instance of anything?

What set does null belong to?

How is it represented in the memory?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

What is null?

It is nothing.

Is null an instance of anything?

No as it is nothing It can't be instance of any thing.

What set does null belong to?

No any set

How is it represented in the memory?

If some reference points to it like:

Object o=new Object();

In heap memory some space assigned to new created object. And o will point to that assigned space in memory.

Now o=null;

This means now o will not point to that memory space of object.

Solution 4 - Java

No it's not the instance of anything, instanceof will always be false.

Solution 5 - Java

Null in Java(tm)

In C and C++, "NULL" is a constant defined in a header file, with a value like:

    0

or:

    0L

or:

    ((void*)0)

depending on the compiler and memory model options. NULL is not, strictly speaking, part of C/C++ itself.

In Java(tm), "null" is not a keyword, but a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type.

Solution 6 - Java

The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.

Also maybe have a look at

null : Java Glossary

Solution 7 - Java

Null is not an instance of any class.

However, you can assign null to variables of any (object or array) type:

 // this is false   
 boolean nope = (null instanceof String);

 // but you can still use it as a String
 String x = null;
 "abc".startsWith(null);

Solution 8 - Java

Bytecode representation

Java's null has direct JVM support: three instructions are used to implement it:

  • aconst_null: e.g. to set a variable to null as in Object o = null;
  • ifnull and ifnonnull: e.g. to compare an object to null as in if (o == null)

Chapter 6 "The Java Virtual Machine Instruction Set " then mentions the effects of null on other instructions: it throws a NullPointerException for many of them.

2.4. "Reference Types and Values" also mentions null in generic terms:

> A reference value may also be the special null reference, a reference to no object, which will be denoted here by null. The null reference initially has no run-time type, but may be cast to any type. The default value of a reference type is null.

Solution 9 - Java

null is special value, it is not instance of anything. For obviously reason it cannot be instanceof anything.

Solution 10 - Java

null is a special value that is not an instance of any class. This is illustrated by the following program:

public class X {
   void f(Object o)
   { 
      System.out.println(o instanceof String);   // Output is "false"
   }
   public static void main(String[] args) {
      new X().f(null);
   }
}

Solution 11 - Java

There are two major categories of types in Java: primitive and reference. Variables declared of a primitive type store values; variables declared of a reference type store references.

String x = null;

In this case, the initialization statement declares a variables “x”. “x” stores String reference. It is null here. First of all, null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.

Solution 12 - Java

null in Java is like/similar to nullptr in C++.

Program in C++:

class Point
{
    private:
       int x;
       int y;
    public:
       Point(int ix, int iy)
       {
           x = ix;
           y = iy;
       }
       void print() { std::cout << '(' << x << ',' << y << ')'; }
};
int main()
{
    Point* p = new Point(3,5);
    if (p != nullptr)
    {
       p->print();
       p = nullptr;
    }
    else
    {
        std::cout << "p is null" << std::endl;
    }
    return 0;
}

Same program in Java:

public class Point {
    private int x;
    private int y;
    public Point(int ix, int iy) {
        x = ix;
        y = iy;
    }
    public void print() { System.out.print("(" + x + "," + y + ")"); }
}
class Program
{
    public static void main(String[] args) {
        Point p = new Point(3,5);
        if (p != null)
        {
            p.print();
            p = null;
        }
        else
        {
            System.out.println("p is null");
        }
    }
}

Now do you understand from the codes above what is null in Java? If no then I recommend you to learn pointers in C/C++ and then you will understand.

Note that in C, unlike C++, nullptr is undefined, but NULL is used instead, which can also be used in C++ too, but in C++ nullptr is more preferable than just NULL, because the NULL in C is always related to pointers and that's it, so in C++ the suffix "ptr" was appended to end of the word, and also all letters are now lowercase, but this is less important.

In Java every variable of type class non-primitive is always reference to object of that type or inherited and null is null class object reference, but not null pointer, because in Java there is no such a thing "pointer", but references to class objects are used instead, and null in Java is related to class object references, so you can also called it as "nullref" or "nullrefobj", but this is long, so just call it "null".

In C++ you can use pointers and the nullptr value for optional members/variables, i.e. member/variable that has no value and if it has no value then it equals to nullptr, so how null in Java can be used for example.

Solution 13 - Java

An interesting way to see null in java in my opinion is to see it as something that DOES NOT denote an absence of information but simply as a literal value that can be assigned to a reference of any type. If you think about it if it denoted absence of information then for a1==a2 to be true doesn't make sense (in case they were both assigned a value of null) as they could really could be pointing to ANY object (we simply don't know what objects they should be pointing to)... By the way null == null returns true in java. If java e.g. would be like SQL:1999 then null==null would return unknown (a boolean value in SQL:1999 can take three values : true,false and unknown but in practise unknown is implemented as null in real systems)... http://en.wikipedia.org/wiki/SQL

Solution 14 - Java

Short and precise answer which answers all your questions formally from JLS:

> > 3.10.7. The Null Literal > > The null type has one value, the null reference, represented by the > null literal null, which is formed from ASCII characters. >
> A null literal is always of the null type.

Only a reference of type which is assigned to null is allocated. You don't assign any value (object) to the reference. Such allocation is specific to JVM how much reference will take and in which memory area it will be allocated.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionunj2View Question on Stackoverflow
Solution 1 - JavapolygenelubricantsView Answer on Stackoverflow
Solution 2 - JavaStephen CView Answer on Stackoverflow
Solution 3 - JavaSanjay JainView Answer on Stackoverflow
Solution 4 - JavaTomView Answer on Stackoverflow
Solution 5 - Javap27View Answer on Stackoverflow
Solution 6 - JavaAdriaan StanderView Answer on Stackoverflow
Solution 7 - JavaThiloView Answer on Stackoverflow
Solution 8 - JavaCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 9 - JavafastcodejavaView Answer on Stackoverflow
Solution 10 - JavaItay MamanView Answer on Stackoverflow
Solution 11 - JavaAnandView Answer on Stackoverflow
Solution 12 - Javauser2133061View Answer on Stackoverflow
Solution 13 - JavaBat0u89View Answer on Stackoverflow
Solution 14 - JavaOleksii KyslytsynView Answer on Stackoverflow