0
0
Javaprogramming~10 mins

Type promotion in Java - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Type promotion
Declare smaller type variable
Use in expression with larger type
Java promotes smaller type to larger type
Expression evaluated as larger type
Assign result to compatible type variable
Java automatically converts smaller data types to larger ones in expressions to avoid data loss.
Execution Sample
Java
byte b = 10;
int i = b + 5;
System.out.println(i);
Adds a byte and an int; byte is promoted to int before addition.
Execution Table
StepExpressionType BeforeType After PromotionValueAction
1bbytebyte10Variable declared
25intint5Literal int
3b + 5byte + intint + int15b promoted to int, addition done
4i = b + 5intint15Assign result to int variable
5System.out.println(i)intint15Print value
💡 Execution ends after printing the promoted and calculated int value 15.
Variable Tracker
VariableStartAfter ExpressionFinal
b10 (byte)10 (byte)10 (byte)
iuninitialized15 (int)15 (int)
Key Moments - 2 Insights
Why does Java promote 'byte' to 'int' in the expression 'b + 5'?
Java promotes smaller types like byte to int in arithmetic expressions to avoid data loss and to use a common type for calculation, as shown in execution_table row 3.
Can we assign the result of 'b + 5' directly back to a byte variable without casting?
No, because after promotion the result is int, which is larger than byte. Assigning int to byte without cast causes error, as shown in execution_table row 4 where 'i' is int.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the type of 'b + 5' after promotion?
Aint
Bbyte
Cshort
Dlong
💡 Hint
Check the 'Type After Promotion' column in execution_table row 3.
At which step is the value 15 assigned to variable 'i'?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column for assignment in execution_table.
If 'b' was declared as int instead of byte, how would the promotion step change?
APromoted to long
BNo promotion needed, both are int
CPromoted to byte
DPromoted to double
💡 Hint
Refer to variable_tracker and execution_table type columns for type changes.
Concept Snapshot
Type promotion in Java:
- Smaller types (byte, short, char) promoted to int in expressions
- Ensures safe arithmetic without data loss
- Result type is at least int
- Assigning back to smaller type needs explicit cast
- Common in arithmetic and mixed-type expressions
Full Transcript
This example shows how Java promotes smaller types like byte to int when used in expressions. The variable 'b' is a byte with value 10. When added to the int literal 5, Java promotes 'b' to int before addition. The result is an int value 15, which is assigned to the int variable 'i'. Finally, printing 'i' outputs 15. This automatic type promotion prevents data loss during calculations and is a key behavior in Java arithmetic.