8

I know that null is not a data type.

But null can be only assigned for any type of Object and String.

Example:

Object o = null; // it tells that null is an object
String b = null; // it tells that null is of string type

Here null can be assigned to both an Object and a String, but if I want to put assign any object into String we have to use type cast. but for null there is no type case. something like the following

String b =(String) o;

Thats why I have doubt that which type of data type is null. How null can be assigned to any object or any String. How is null implemented in Java?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614

2 Answers2

9

The null reference and keyword are Java built-in constructs and are treated specially by the compiler. The compiler then emits the corresponding bytecode instructions depending on the context which null is used in.

Note that this behavior is different from older languages such as C or C++03 where NULL pointer was simply a zero constant.

Karel Petranek
  • 15,005
  • 4
  • 44
  • 68
  • how null can be assigned to any type of Object? –  Jul 18 '11 at 07:19
  • 8
    @Deepakkk - because the JLS says it can. – Stephen C Jul 18 '11 at 07:21
  • @Deepakkk: Edited to clarify a bit, hopefully it makes better sense for you now – Karel Petranek Jul 18 '11 at 07:22
  • 3
    Doesn't "built-in constructs and are treated specially by the compiler" answer your question? – nnnnnn Jul 18 '11 at 07:22
  • Actually, there is only one context in which `null` can be used: as an expression of any reference type (e.g. assigning to a reference variable, passing as a reference parameter, casting to a reference type, comparing to a reference variable). There is no special-casing by the compiler here for different contexts. – Paŭlo Ebermann Aug 31 '11 at 23:43
2
Object o = null; // it tells that null is an object
String b = null; // it tells that null is of string type

Neither of those comments is correct. All that's happening here is that references are being set to null.

user207421
  • 305,947
  • 44
  • 307
  • 483