Java has no sizeof operator to find the size of primitive data types but all Java primitive wrappers except Boolean
provide a SIZE
constant in bits that could be divided by eight to get the size of a data type in bytes. Moreover, since Java 8, all primitive wrapper classes (except Boolean
) have a BYTES
constant, which gives data type's size in bytes. So you can use that also once you have been moved to Java 8. Following is a trivial Java program demonstrating the size of primitive data types through their primitive wrappers.
class SizePrimitiveTypes { public static void main (String[] args) { System.out.println("Size of byte: " + (Byte.SIZE/8) + " bytes."); System.out.println("Size of short: " + (Short.SIZE/8) + " bytes."); System.out.println("Size of int: " + (Integer.SIZE/8) + " bytes."); System.out.println("Size of long: " + (Long.SIZE/8) + " bytes."); System.out.println("Size of char: " + (Character.SIZE/8) + " bytes."); System.out.println("Size of float: " + (Float.SIZE/8) + " bytes."); System.out.println("Size of double: " + (Double.SIZE/8) + " bytes."); } } OUTPUT ====== D:\JavaPrograms>javac SizePrimitiveTypes.java D:\JavaPrograms>java SizePrimitiveTypes Size of byte: 1 bytes. Size of short: 2 bytes. Size of int: 4 bytes. Size of long: 8 bytes. Size of char: 2 bytes. Size of float: 4 bytes. Size of double: 8 bytes.
Note that size of primitive types in Java is always the same. It is not platform dependent. Also, all primitive data types in Java are signed. Java does not support unsigned types.
Hope you have enjoyed reading How to find the size of a primitive data type in Java? Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!
Share this page on WhatsApp