Introduction
Java Program to Display Size of Different Data Types
A Java program to display the size (in bits and bytes) of primitive data types.
Problem Description
Write a Java program to display the size of various primitive data types like int, float, double, char, etc.
Code
public class DataTypeSizes {
public static void main(String[] args) {
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.");
System.out.println("Size of short: " + (Short.SIZE / 8) + " bytes.");
System.out.println("Size of byte: " + (Byte.SIZE / 8) + " bytes.");
}
}Output
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.
Size of short: 2 bytes.
Size of byte: 1 bytes.Explanation
- Wrapper Classes: Java provides wrapper classes for primitive types (e.g.,
Integerforint,Doublefordouble). SIZEConstant: These wrapper classes have a constantSIZEwhich holds the size of the type in bits.- Calculation: Dividing the size in bits by 8 gives the size in bytes.
Try Yourself
- Bits: Modify the program to print the size in bits instead of bytes.
- Range: Can you print the minimum and maximum values for
int? Hint: UseInteger.MIN_VALUEandInteger.MAX_VALUE. - Boolean: Try to find
Boolean.SIZE. Does it exist? Why or why not? - String: Can you find the size of a
String? (Hint: It's not a primitive type). - Brain Twister: If
shortis 2 bytes (16 bits), calculate its maximum positive value manually ($2^15 - 1$). Does it matchShort.MAX_VALUE?
