Search code examples
javaclassobjecttypesinteger

In Java, a primitive data type like "int" a class or an object?


I read that primitive Java types (boolean, byte, char, short, int, long, float, and double) and the keyword void are also represented as class Class objects. Then it means that int is an object of class Class then how come following statement doesn't throw error because .class is only used with class name?

Class c = int.class

Solution

    • int is a numeric type.
    • int.class is a class literal.

    A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a . and the token class.

    ClassLiteral:

    • TypeName {[ ]} . class
    • NumericType {[ ]} . class
    • boolean {[ ]} . class
    • void . class

    JLS 10 - 15.8.2. Class Literals

    Moreover,

    Class<Integer> intClass = int.class;
    

    according to

    The type of p.class, where p is the name of a primitive type (§4.2), is Class<B>, where B is the type of an expression of type p after boxing conversion (§5.1.7).

    JLS 10 - 15.8.2. Class Literals