Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a primitive class and primitive data type?

I am reading a book on Java, and they seem to use the two terms "primitive class" and "primitive data type" interchangeably.

What's the difference between the two? I understand that Integer is a wrapper class, and people reference int as a primitive data type. So is it also a primitive class?

like image 987
Luke Thistlethwaite Avatar asked Aug 02 '17 15:08

Luke Thistlethwaite


2 Answers

They're confusing their vernacular here.

A primitive is a data type which is not an object. int, float, double, long, short, boolean and char are examples of primitive data types. You can't invoke methods on these data types and they don't have a high memory footprint, which is their striking difference from classes.

Everything else is a class (or class-like in the case of interfaces and enums). Pretty much everything that begins with an upper-case letter, like String, Integer are classes. Arrays also classify as not-primitives, even though they may hold them. int[] isn't a primitive type but it holds primitives.

The only thing that could realistically come close would be the wrapper classes, as explained by the JLS, but even then, they're still classes, and not primitives.

like image 107
Makoto Avatar answered Oct 09 '22 23:10

Makoto


Primitive class has a special meaning in the context of reflection APIs: when you need to retrieve a method that takes a parameter of primitive type, you need a primitive class object that corresponds to that primitive type.

This is important if you must distinguish between overloads that take primitives and overloads that take wrappers:

void someMethod(int n);
void someMethod(Integer n);

There are two ways to obtain this class object:

  • Using class literal, e.g. int.class, or
  • Using TYPE member of the corresponding wrapper class, e.g. Integer.TYPE.

This is not the same class as the class representing the primitive wrapper. In other words,

int.class != Integer.class
like image 24
Sergey Kalinichenko Avatar answered Oct 10 '22 00:10

Sergey Kalinichenko