2.5 Type Casting
When programming, there are times when you need to perform an operation between variables or literals of different types. In such cases, you must first match the values to the same type before executing the operation. Converting the type of a variable or literal to another type like this is called Type Casting.
1. Casting Operator
Casting can be performed explicitly, but if there is no chance of data loss, the compiler will also apply casting automatically. When performing casting explicitly (forced casting), you place (type) before the value.
double d = 85.4;
int score = (int) d;
// The space of 'd' does not change, only the value is converted
System.out.println("score=" + score); // 85 (decimal points are dropped)
System.out.println("d=" + d); // 85.4 (the value is preserved)
2. Implicit Casting (Automatic Conversion)
There are cases where you can omit the casting operator when assigning a value between variables of different types. 'Implicit casting' refers to when the compiler handles the conversion on its own. Usually, because it is safe to convert "from a type with a narrow expression range to a type with a wide one", it is automatically converted.
Rules of Implicit Casting
byte->short/char->int->long->float->double
The further to the right, the wider the range of values that can be expressed, so it is automatically converted. Even though the float type is 4 bytes in size, it takes precedence over long (8 bytes) because the floating-point method covers a much wider range of values.
int i = 300;
double d1 = i; // Converts safely from int (4 bytes) to double (8 bytes)
System.out.println(d1); // 300.0
3. Explicit Casting (Forced Conversion)
Conversely, when there is a risk of losing a value (like pouring water from a large bowl into a smaller one), the Java compiler throws an error. In this instance, the developer must explicitly state that they will convert despite the potential data loss.
double d = 3.14;
// int i = d;
// Error occurs: Incompatible types. Possible lossy conversion from double to int
int i = (int) d; // Explicit type casting specified
System.out.println(i); // Fortunately 3 is printed without errors (fractional part is discarded)
Integer Overflow and Casting
When a value is forcefully truncated, unpredictable values will arise if it exceeds the range of the storage space.
int exceed = 300;
byte b = (byte) exceed;
System.out.println(b); // 44 (unexpected value caused by data loss)
Summary
- Conversion from a smaller type to a larger type: Implicit Casting (Safe)
- Conversion from a larger type to a smaller type: Explicit Casting Needed (Risk of data loss)