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

Samsung Galaxy S8 hides home button and gains Bixby AIPosted on Wednesday March 29, 2017

The latest flagship phones from Samsung feature bigger screens and a new kind of virtual assistant.

Samsung Galaxy S8 - but is it art? The internet reactsPosted on Wednesday March 29, 2017

The experts and public respond to the newly unveiled Samsung Galaxy S8 and S8+ smartphones.

Virgin Media overstated superfast broadband rolloutPosted on Wednesday March 29, 2017

Virgin Media suspends four employees after it emerged it overstated its superfast broadband rollout.

Courtesy BBC News