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

UK seeks future cyber-security starsPosted on Friday November 17, 2017

UK initiatives aim to get young people choosing a career in cyber-security to close a looming skills gap.

Apple delays launch of smart speakerPosted on Friday November 17, 2017

The HomePod will now go on release in early 2018 as the gadget still needs work, said Apple.

Germany bans children's smartwatchesPosted on Friday November 17, 2017

Telecoms regulator says kids' smartwatches are spying devices and are to be banned under German law.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×