user2044296
user2044296

Reputation: 524

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

Upvotes: 3

Views: 1655

Answers (3)

user9772728
user9772728

Reputation: 1

Java is a strong typed language, that's why variables must

to be defined before use in the program later.

Variables are the buckets or the containers which reserved memory locations to store values in computer memory. When you create a variable you reserve some space in the memory of the computer.

On the bases of the data type of a variable, Your operating system allocates memory and store the value in the reserved memory.

There are two data types available in Java:−

1) Primitive Data Types 2) Reference/Object Data Types

There are eight primitives in Java:

byte (number, 1 byte) short (number, 2 bytes) int (number, 4 bytes) long (number, 8 bytes) float (float number, 4 bytes) double (float number, 8 bytes) char (a character, 2 bytes) boolean (true or false, 1 byte)

Checkout the Video Tutorial for Primitive data types in java

Upvotes: -2

Andrew
Andrew

Reputation: 49656

  • 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

Upvotes: 8

Gatusko
Gatusko

Reputation: 2608

This is because of Class all primitives have this. Like said in the document.

The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

This is useful for reflection. That is why you can use int.class and all primitives types. So all primitives have a class... Even if they are primitives. Kind of confusing but useful in reflection for knowing if it is a int.class or a Integer.class

Upvotes: 0

Related Questions