Start Coding Now

Type Casting in Java - Widening and Narrowing

Understand type conversion in Java. Learn about implicit (widening) and explicit (narrowing) casting with examples.

What is Type Casting?

Type casting is when you assign a value of one primitive data type to another type.

1. Widening Casting (Automatically)

Converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double

int myInt = 9;
double myDouble = myInt; // Automatic casting: 9.0

2. Narrowing Casting (Manually)

Converting a larger type to a smaller size type. double -> float -> long -> int -> char -> short -> byte

double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: 9

Frequently Asked Questions