JDelage
JDelage

Reputation: 13672

Java - is `null` an instance of `object`?

I read that null isn't an instanceof anything, but on the other hand that everything in Java extends Object class.

Upvotes: 37

Views: 28690

Answers (7)

Mitali Jain
Mitali Jain

Reputation: 49

Hoping that this example clears your doubt :

public void printObject(Object object) {
    System.out.println("object referred");
}

public void printObject(double[] doubleArray) {
    System.out.println("Array of type double");
}

public static void main(String[] args) {
    JavaNullObjectTest javaNullObjectTest = new JavaNullObjectTest();

    javaNullObjectTest.printObject(null); //Array of type double

    javaNullObjectTest.printObject((Object)null); //object referred
}

We can but, convert a 'null' to object.

Upvotes: 0

user467871
user467871

Reputation:

No, it is a reference. null is not an object

String s = null;

System.out.println(s instanceof Object); // false

Upvotes: 61

NPE
NPE

Reputation: 500437

In a word, no.

Peter Norvig's Java IAQ addresses this question in some detail (specifically "Q: Is null an Object?")

Upvotes: 11

Donal Fellows
Donal Fellows

Reputation: 137587

As the JLS says, null is of the null type and that is not a reference type. It is however usable in situations where a value of a reference type is expected (the value is really a “bottom” in the type algebra).

Upvotes: 1

saugata
saugata

Reputation: 2863

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

Java Language Specification

Upvotes: 5

mikej
mikej

Reputation: 66263

No, null is not an object. It is a literal that means that a variable does not reference any object.

Upvotes: 2

stacker
stacker

Reputation: 68962

Null means that you don't have a reference to an object.

Object o = null;

o is a reference but there is no object referenced and no memory allocated for it.

o = new Object();

o is still a reference and holds the adress where the object is located in memory

Upvotes: 3

Related Questions