Forums Register Login

Null is not an instanceof Object

+Pie Number of slices to send: Send
We can return null in a method with an object reference return type.


public Button doStuff()

{

return null; // how does this work fine , if null is not an instanceof Object
}

+Pie Number of slices to send: Send
here null means, reference not pointing to any object in the heap. so for any type of object reference we can say that it is not pointing to any object. hope helps.
+Pie Number of slices to send: Send
NULL is a special literal of the null type.

1- It can be cast to any reference type, but not to any primitive type such as int or boolean.
2- It is impossible to cast to the null type or declare a variable of this type.
+Pie Number of slices to send: Send
null is an instanceof object gives false.

Then when an Button object is expected as a return type, how could we pass null.

I feel null is an object because of the code below ???

public class ListTest {



public static void main(String args[])
{
List lt = new ArrayList();
lt.add(null);// add method takes only an object.
}



}


I had asked this question previously but couldnt get any satisfactory answers.
+Pie Number of slices to send: Send
null can be cast to any object type without a ClassCastException.
+Pie Number of slices to send: Send

I think the issue that the OP is having is trying to classify what is the type of "null" -- as it seems to have some contradictory behaviors.

IMHO, I think it is easier to think of null as a literal, that can be cast to any object type, can be assigned to any object type, but when used with the instanceof operation, it always return false. I don't think it is correct to think of it as an object (or not an object). I think it may be best to think of it as a literal that has special behaviors.

Henry
+Pie Number of slices to send: Send
Note that "instanceof" is generally irrelevant to the question of whether code will compile, as "instanceof" is a runtime operation (true, the compiler will reject impossible uses of instanceof between incompatible types.) In the case of null, though, the key thing is, as has been pointed out, that you can legally cast null to any reference type, and code is compiled based only on reference types (or "compile-time types.") The runtime type of an object, or the presence or absence of an object at all, has nothing whatsoever to do with compilation.
That feels good. Thanks. Here's a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1558 times.
Similar Threads
NullPointerException when removing objects, for which equals() is overriden, from JComboBox
null & instanceof
Passing dynamically created arguments to method
equals(Object) of String
null instanceof an Object ?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 17:29:30.