Implicit Widening in Assignments and Expressions
What you'll learn: How Java automatically converts smaller numeric types to larger ones during assignments and calculations.
When you work with different primitive types together, Java doesn't make you manually convert everything—it helps you out by automatically widening smaller types to larger ones when it's safe to do so.
The Assignment Scenario
When you assign a smaller type to a larger type variable, Java widens it automatically:
int myInt = 42;
long myLong = myInt; // int automatically widens to long
double myDouble = myInt; // int automatically widens to double
The compiler sees that an int fits perfectly into a long or double without losing information, so it performs the conversion silently. This is safe because you're moving to a "bigger container."
The Expression Scenario
Widening also happens during arithmetic operations when you mix types:
int a = 10;
long b = 20L;
long result = a + b; // 'a' widens to long before addition
Before the addition happens, Java promotes a from int to long so both operands match. The result is naturally a long.
int x = 5;
double y = 2.5;
double z = x + y; // 'x' widens to double before addition
Here, x becomes a double temporarily for the calculation, and the result is a double.
The Rule
Java only widens automatically—never narrows. It goes from smaller capacity to larger (byte → short → int → long → float → double), ensuring no data loss occurs without your explicit permission.
Key Takeaway: Java automatically widens smaller numeric types to larger ones in assignments and expressions, making mixed-type operations seamless and safe without explicit casting.