Type Casting
TL;DR
- Implicit Casting (Widening): Automatic conversion of a smaller data type to a larger data type (e.g.,
inttodouble). No data loss. - Explicit Casting (Narrowing): Manual conversion of a larger data type to a smaller data type (e.g.,
doubletoint). Requires a cast operator(type)and may cause data loss.
Concept
Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting:
1. Widening Casting (Automatically)
Converting a smaller type to a larger type size. Java does this automatically because there is no risk of losing data.
byte -> short -> char -> int -> long -> float -> double
2. Narrowing Casting (Manually)
Converting a larger type to a smaller size type. You must manually cast this by placing the type in parentheses (). This is because a larger type might contain a value that doesn’t fit in the smaller type, resulting in truncated data.
double -> float -> long -> int -> char -> short -> byte
Examples
public class CastingExample {
public static void main(String[] args) {
// --- Widening (Automatic) ---
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
// --- Narrowing (Manual) ---
double anotherDouble = 9.78d;
int anotherInt = (int) anotherDouble; // Manual casting: double to int
System.out.println(anotherDouble); // Outputs 9.78
System.out.println(anotherInt); // Outputs 9 (Fractional part is lost!)
}
}
Interview Questions
Q: What happens to a float or double when cast to an int?
A: The fractional part is completely truncated (discarded). It does not round up or down. For example, (int) 9.99 becomes 9.
Q: What happens if you cast a number to a byte but the number is larger than the maximum byte value (127)?
A: The value wraps around (overflows). A byte is 8 bits. If you cast 130 to a byte, it wraps around the binary bounds and results in -126.