Type promotion helps Java automatically convert smaller data types to bigger ones so calculations work smoothly without errors.
0
0
Type promotion in Java
Introduction
When adding a byte and an int together in a calculation.
When comparing a short with an int in an if statement.
When assigning a char value to an int variable.
When mixing different numeric types in arithmetic expressions.
Syntax
Java
int result = byteValue + intValue;Java automatically converts smaller types like byte or short to int before arithmetic.
This avoids data loss and makes calculations safe.
Examples
The byte 'b' is promoted to int before adding to 'i'. The result is int.
Java
byte b = 10; int i = 20; int sum = b + i;
Both short and char are promoted to int before addition.
Java
short s = 5; char c = 'A'; int result = s + c;
float is promoted to double before addition, so result is double.
Java
float f = 3.5f; double d = 4.5; double total = f + d;
Sample Program
This program shows how Java promotes smaller types to bigger types automatically during arithmetic operations.
Java
public class TypePromotionExample { public static void main(String[] args) { byte b = 10; short s = 20; char c = 'A'; // ASCII 65 int i = 30; float f = 40.5f; double d = 50.5; int result1 = b + s; // byte and short promoted to int int result2 = s + c; // short and char promoted to int double result3 = f + d; // float promoted to double System.out.println("Result1 (byte + short): " + result1); System.out.println("Result2 (short + char): " + result2); System.out.println("Result3 (float + double): " + result3); } }
OutputSuccess
Important Notes
Type promotion happens automatically in expressions involving byte, short, and char.
When mixing float and double, float is promoted to double.
Be careful: promotion can sometimes cause unexpected results if you assume types stay the same.
Summary
Java automatically converts smaller types to bigger types in expressions to avoid errors.
byte, short, and char are promoted to int before arithmetic.
float is promoted to double when mixed in expressions.