Type Casting πͺ£¶
Mentor's Note: Type casting is the process of moving data from one type of "Box" to another. Sometimes itβs easy and safe, and sometimes you have to "Force" it, which can cause data to spill and be lost! π‘
π The Scenario: The Bucket & Glass Challenge π¶
Imagine you are moving water between different containers.
- Widening (The Safe Move): You pour water from a Small Glass (
int) into a Large Bucket (double). π The bucket has plenty of room, so the water fits perfectly. No spills! β - Narrowing (The Dangerous Move): You pour water from a Full Bucket (
double) back into a Small Glass (int). π« If the bucket has more than the glass can hold, you Spill (Lose) the extra water! - The Result: You must be careful when moving data "Downwards" to avoid losing information. β
π¨ Visual Logic: The Casting Hierarchy¶
graph LR
A[byte] --> B[short]
B --> C[char]
C --> D[int]
D --> E[long]
E --> F[float]
F --> G[double]
G -- "MANUAL π«" --> A
| Type | Safety | Java Name | Action |
|---|---|---|---|
| Smaller to Larger | Safe β | Widening | Automatic |
| Larger to Smaller | Risky β οΈ | Narrowing | Manual (type) |
π Concept Explanation¶
1. Widening Casting (Automatic) π¶
Converting a smaller type to a larger type size. Java does this for you automatically because there is no risk of data loss.
- Example: int (9) to double (9.0).
2. Narrowing Casting (Manual) βοΈ¶
Converting a larger type to a smaller type size. This must be done manually by placing the type in parentheses () in front of the value.
- Example: double (9.78) to int (9).
π» Implementation: The Casting Lab¶
// π Scenario: Moving data across types
// π Action: Automatic vs Manual casting
public class Main {
public static void main(String[] args) {
// π 1. Widening (Automatic)
int smallVal = 100;
double largeVal = smallVal; // int -> double
System.out.println("Automatic: " + largeVal); // 100.0
// βοΈ 2. Narrowing (Manual)
double myDouble = 9.99;
int myInt = (int) myDouble; // double -> int
System.out.println("Manual: " + myInt); // 9 (Lost the .99!)
}
}
π Sample Dry Run (Data Loss)¶
| Initial Type | Value | Target Type | Cast Used | Final Value | Logic |
|---|---|---|---|---|---|
double |
15.75 |
int |
(int) |
15 |
Decimals are cut off βοΈ |
int |
127 |
byte |
(byte) |
127 |
Fits in range β |
int |
300 |
byte |
(byte) |
44 |
OVERFLOW! (Spilled) π« |
π Technical Analysis: Truncation vs Rounding π§ ¶
When casting a double or float to an int, Java Truncates the number. This means it just cuts off everything after the decimal point. It does NOT round to the nearest number!
- 9.99 becomes 9.
- -1.99 becomes -1.
π― Practice Lab π§ͺ¶
Task: The Average Calculator
Task: You have three int scores: 80, 90, 85. Calculate the average and store it in a double variable.
Goal: Use widening to make sure your average has decimal points! π‘
π‘ Interview Tip π¶
"Interviewers often ask: 'Can we cast a String to an int using (int)?' Answer: NO. You cannot cast reference types to primitives like that. To convert a String "10" to an int, you must use
Integer.parseInt("10")."
π‘ Pro Tip: "Widening is like a gift from Javaβit's free and safe. Narrowing is like a surgeryβyou must do it yourself and there might be side effects!" - Vishnu Damwala