Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java primitive data types size

Tags:

java

Hi I am learning Java basics. I need to check the size of primitive data types like using sizeof(); in c language.

Example code:

int i;
System.out.print(sizeof(i));
like image 587
Prakash Bala Avatar asked Aug 19 '15 11:08

Prakash Bala


2 Answers

Use the BYTES constants (since Java 8) in the corresponding boxed classes:

sizeof(int) -> Integer.BYTES
sizeof(long) -> Long.BYTES
sizeof(char) -> Character.BYTES
sizeof(short) -> Short.BYTES
sizeof(float) -> Float.BYTES
sizeof(double) -> Double.BYTES
sizeof(byte) -> Byte.BYTES

Note that reference and boolean sizes are not defined, it's implementation-specific. In general you rarely should care about their size.

like image 126
Tagir Valeev Avatar answered Oct 04 '22 21:10

Tagir Valeev


There's no need for such a thing in Java since the sizes of the primitives are set for all JVMs (unlike C where they can vary).

char is 16 bit (actually an unsigned quantity), int is 32 bit, long is 64 bit.

boolean is the ugly sister in all this. Internally it is manipulated as a 32 bit int, but arrays of booleans use 1 byte per element.

like image 34
Bathsheba Avatar answered Oct 04 '22 22:10

Bathsheba