1.

Does size of operator exist in Java?

Answer»

No, sizeof operator doesn’t exist in Java.

All PRIMITIVE data types in Java such as int, char, float, double, long, short have a predefined size in Java. Hence there is no SPECIFIC requirement of the sizeof operator.

Also, in Java, size of the primitive data types is independent of the platform i.e. Windows, Linux.

An int variable will take 4 bytes in both 32 and 64 bit and in both Windows and Linux operating systems.

The size of boolean is not fixed and depends on the JVM. Different JVMs might have different boolean size. Mostly the size of boolean is 1 bit.

Here are a few primitive data types with their fixed sizes

Data typeDefault size
char2 bytes
byte1 byte
short2 byte
int4 bytes
long8 bytes
float4 bytes
double8 bytes
boolean1 bit

Since Java 8, all primitive wrapper classes provide a SIZE constant in bits. Since 1 byte= 8 bits, we divide the constant by 8 to obtain the size of the wrapper class in bytes.

public class Example {  public static void MAIN (STRING[] args)  {    System.out.println(" char: " + (Character.SIZE/8) + " bytes");    System.out.println(" byte: " + (Byte.SIZE/8) + " bytes");    System.out.println(" short: " + (Short.SIZE/8) + " bytes");    System.out.println(" int: " + (Integer.SIZE/8) + " bytes");    System.out.println(" long: " + (Long.SIZE/8) + " bytes");    System.out.println(" float: " + (Float.SIZE/8) + " bytes");    System.out.println(" double: " + (Double.SIZE/8) + " bytes");  } }

The output of the program is as follows:

$javac Example.java $java Example char: 2 bytes byte: 1 bytes short: 2 bytes int: 4 bytes long: 8 bytes float: 4 bytes double: 8 bytes


Discussion

No Comment Found