When I started out using Java, it was implied to me that we have two different types:
Objects (strings, from classes, println, etc)
primitive values (int, double, char)
I just got back an exam from a Professor where this difference would mean the difference between two choices as answers. When I asked my professor to clarify, he told me that primitive values can be objects.
Who is right here and can anyone give me any proof? Proof would be something official sounding and I would choose that as the answer as well as awarding you some proverbial internets.
Primitives are not objects. Which is to say, an int
is not an Integer
.
However, with any vaguely-recent Java compiler, a primitive can be auto-boxed as an associated object type (int
autoboxes as Integer
) and auto-unboxed (Integer
unboxes as int
), and the instances of the object types related to primitives (Integer
, Long
, etc.) are immutable (which is important for behaving like their primitive counterparts), and so the distinction becomes blurry. That may have been what the professor was alluding to.
That is, a method (for instance) accepting an int
can be given an Integer
and the compiler just handles unboxing it; similarly, a method accepting an Object
(maps come to mind) can accept a primitive, and the compiler boxes it into the corresponding object type.
Can a primitive value be considered an object?
The answer is No.
The JLS states
There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
Those are Primitive Types and Values which are
predefined by the Java programming language and named by its reserved keyword
and Reference Types and Values which can be one of
class types (§8), interface types (§9), type variables (§4.4), and array types (§10).
Note also that there is a special type which is the null type
and its corresponding value the null reference
There is also a special null type, the type of the expression null (§3.10.7, §15.8.1), which has no name.
...
The null reference is the only possible value of an expression of null type.
For the primitive types the JLS has defined a mechanism called Boxing Conversion for converting them into the corresponding reference types.
Boxing conversion converts expressions of primitive type to corresponding expressions of reference type.
So since there is the need for a conversion to go from a primitive type to a corresponding reference type one cannot say that primitives can be considered as objects and vice versa. But one can say they are convertible.
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