SyntaxStudy
Sign Up
Java Primitive Data Types and Literals
Java Beginner 1 min read

Primitive Data Types and Literals

Java has eight primitive data types: byte, short, int, long, float, double, char, and boolean. These types store their values directly on the stack (or inline in an object) rather than as heap references. Choosing the right type matters for memory efficiency and for avoiding overflow or precision errors. For example, integer arithmetic on an int will silently overflow if the result exceeds 2,147,483,647; using long avoids this. Literals are the fixed values you write directly in source code. Integer literals can be written in decimal (42), hexadecimal (0x2A), binary (0b00101010), or octal (052). Long literals need an L suffix (42L). Floating-point literals are double by default; append F for float. Underscores can be used inside numeric literals for readability (1_000_000). Character literals use single quotes and support Unicode escapes. Type casting converts a value from one type to another. Widening conversions (e.g. int to long) happen automatically. Narrowing conversions (e.g. double to int) require an explicit cast and may lose information. The Math class provides utility methods such as Math.abs, Math.pow, Math.sqrt, and Math.min/max for common numeric operations.
Example
public class PrimitiveTypes {

    public static void main(String[] args) {

        // Integer family
        byte  b  = 127;                // -128 to 127
        short s  = 32_767;             // -32768 to 32767
        int   i  = 2_147_483_647;      // ~2.1 billion
        long  l  = 9_223_372_036_854_775_807L; // ~9.2 quintillion

        // Binary and hex literals (Java 7+)
        int flags = 0b0000_1111;       // 15 in binary
        int color = 0xFF_AA_00;        // orange in hex

        // Floating-point family
        float  f  = 3.14F;             // ~7 significant digits
        double d  = 3.141592653589793; // ~15 significant digits

        // Character and boolean
        char    c    = 'A';            // UTF-16 code unit
        char    euro = '€';       // Euro sign
        boolean flag = true;

        // Widening conversion (automatic)
        long fromInt = i;              // int -> long, no cast needed

        // Narrowing conversion (explicit cast, may lose data)
        int truncated = (int) 9.99;    // result: 9 (truncates, not rounds)

        // Arithmetic and overflow demo
        int max  = Integer.MAX_VALUE;
        int wrap = max + 1;            // overflows silently to MIN_VALUE

        System.out.printf("byte: %d, short: %d%n", b, s);
        System.out.printf("int: %d, long: %d%n", i, l);
        System.out.printf("float: %.2f, double: %.15f%n", f, d);
        System.out.printf("char: %c (%d), euro: %c%n", c, (int) c, euro);
        System.out.printf("overflow demo: %d + 1 = %d%n", max, wrap);
        System.out.printf("truncated cast: (int)9.99 = %d%n", truncated);
    }
}