I wrote this line of code in Eclipse Mars for messing purposes:
null.toString();
And I got the following compiler error message:
Cannot invoke toString() on the primitive type null
Which is very strange since null
is not a primitive type nor an object reference as explained here: Is null an Object?
So, just to be sure, I tried to compile such odd line of code using javac
and I got this result:
NullTest.java:3: <nulltype> cannot be dereferenced null.toString(); ^ 1 error
Does somebody know why Eclipse would give such (IMO) misleading compiler error message?
Summary. JavaScript has the primitive types: number , string , boolean , null , undefined , symbol and bigint and a complex type: object .
Primitive types cannot be null. So if you're performing a load from the DB, and the field doesn't have a NOTNULL constraint, you can have null values, which Hibernate will attempt to assign to your variable of primitive type.
So the fact is clear, void IS primitive. If you read the documentation of the isPrimitive() function, it makes it pretty clear that void is not a primitive: "There are nine predefined Class objects to represent the eight primitive types and void.
Since the null-type is a subtype of Object
, it's conceivably OK to invoke Object
methods on null
.
However, following that logic, since the null-type is a subtype of every reference type, we should be allowed to invoke any method of any class/interface on null
. That'll be a mess.
Syntactically, null.toString()
should be recognized as a method invocation expression at first, because null
is a Primary
expression. Then, to determine the class/interface to search for the method toString
, JLS says
...The class or interface to search is T if T is a class or interface type, or the upper bound of T if T is a type variable
It is a compile-time error if T is not a reference type.
T
is the null-type here; it is not a class type, interface type, or type variable, therefore this step should fail.
However, does it fail because T is not a reference type?
Is the null-type a reference type? JLS says
The types ... are divided into two categories: primitive types and reference types
The numeric types are ....
The reference types are class types, interface types, [type variables,] and array types . [period!]
There is also a special null type.
Depending on your parsing of the text, null-type may or may not be a reference type. That is usually not really important; it's just a matter of categorization. But it leads to confusions, for example in this case -- the failure is because T
is not a "proper" reference type, and the compiler deduces by mistake that it must be a primitive type then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With