ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Java Tutorial• 6 min read

Variables, Data Types & Type Casting

8 Primitives vs Reference types, widening vs narrowing conversion

Java has 8 primitive data types (byte, short, int, long, float, double, boolean, char) stored directly on the stack, alongside heap-allocated Reference types (Strings, Arrays, Objects).

Primitive Types & Type Casting

Integral types: byte (8-bit), short (16-bit), int (32-bit), long (64-bit, suffix L).

Floating point: float (32-bit, suffix f), double (64-bit default).

Widening Casting (Automatic): Converting smaller to larger type (e.g. int to double). Zero risk of data loss.

Narrowing Casting (Manual): Converting larger to smaller type (e.g. (int) 9.78 truncates decimals to 9).

Type Casting in Java
public class CastingDemo {
    public static void main(String[] args) {
        // Widening casting (automatic)
        int myInt = 42;
        double myDouble = myInt; // 42.0

        // Narrowing casting (manual truncation)
        double price = 99.95;
        int roundedPrice = (int) price; // 99

        System.out.println("Original: " + price + " -> Truncated: " + roundedPrice);
    }
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the result of narrowing cast `(int) 9.85` in Java?