Type casting is the process of converting a variable or value of one data type into another data type. In Java, type casting is split into two primary mechanisms: Widening (Automatic / Implicit) and Narrowing (Manual / Explicit).
Widening casting occurs automatically when converting a smaller numerical data type to a larger numerical data type. Because the destination type has a larger bit-width, there is zero risk of data overflow:
byte → short → int → long → float → double
public class WideningDemo {
public static void main(String[] args) {
int myInt = 100;
// Automatic widening: int (32-bit) to double (64-bit)
double myDouble = myInt;
System.out.println("Original int: " + myInt); // Output: 100
System.out.println("Widened double: " + myDouble); // Output: 100.0
}
}
Narrowing casting converts a larger data type to a smaller data type. Because data loss, truncation, or bit overflow can occur, the Java compiler refuses to perform this automatically. The developer must explicitly specify the target type in parentheses (target_type):
double → float → long → int → short → byte
public class NarrowingDemo {
public static void main(String[] args) {
double price = 99.95;
// Explicit narrowing cast: truncates decimal fraction
int roundedPrice = (int) price;
System.out.println("Original double: " + price); // 99.95
System.out.println("Narrowed int: " + roundedPrice); // 99 (Decimals dropped!)
// Bit Truncation & Overflow Example:
int bigVal = 130;
byte smallByte = (byte) bigVal;
System.out.println("130 cast to byte: " + smallByte); // Output: -126!
}
}
When evaluating arithmetic expressions, Java automatically promotes operand types to avoid intermediate overflow:
byte, short, and char values are automatically promoted to int.long, the whole expression is promoted to long.float, the whole expression is promoted to float.double, the final result is promoted to double.byte b1 = 50;
byte b2 = 50;
// byte b3 = b1 + b2; // COMPILER ERROR! (b1 + b2) evaluates to int
int b3 = b1 + b2; // Correct!
byte b4 = (byte) (b1 + b2); // Also valid with explicit cast
Exam Question: "Explain why (byte) 130 produces -126 in Java."
Mathematical Explanation:
1. Integer 130 in 32-bit binary: 00000000 00000000 00000000 10000010.
2. Casting to 8-bit byte truncates the top 24 bits, leaving: 10000010.
3. The most significant bit (MSB) is 1, signaling a negative number in two's complement.
4. Two's complement of 10000010 is: invert bits (01111101 = 125) + 1 = 126. With the negative sign, it evaluates to -126!
Now let us explore Java operators, mathematical expressions, bitwise manipulations, and operator precedence. Proceed to: Java Operators & Precedence →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Bit sizes and ranges.
Arithmetic expressions.
Upcasting vs downcasting.
Parsing Strings to numbers.