How to find the size of a primitive data type in Java?

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!




Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

Facebook confusion over fake cancer babies U-turnsPosted on Wednesday February 22, 2017

Facebook apologises after repeatedly restoring posts featuring stolen photos of children and posted claims they had cancer.

A guided tour of the cybercrime undergroundPosted on Wednesday February 22, 2017

Malware researcher Anton talks about who does what in the web's dark marketplaces.

Mouse trap triggers internet alertsPosted on Wednesday February 22, 2017

A pest control company develops a mouse trap that connects to the internet.

Courtesy BBC News