by Tony Sintes

In Java, size doesn’t matter

news
Sep 29, 20001 min

Can you ascertain the size of a primitive in Java?

Q: Is there a method in Java for determining the size of a primitive type, similar to C++’s sizeof operator?

A: The short answer: you can’t find the size of a Java primitive type through a sizeof operator. Instead, all primitive types have a fixed size. Java was designed in this way to facilitate portability. Because Java specifies the primitive size up front, you can write a Java program and run it reliably on any JVM. If the designers had chosen to not define the size of primitive types, a program that ran on one hardware architecture could fail on another.

Another reason for a lack of sizeof: Java handles all memory access for you. As such, there is no need to find the sizeof some primitive or object in order to allocate a space of memory for it.

Nonetheless, times do arise when you will need to know the size of a primitive. For those times, I give you the following table:

TypeSize
boolean1 bit
char16 bit
byte8 bit
short16 bit
int32 bit
long64 bit
float32 bit
double64 bit
The sizes of the various Java primitives