Type Casting & Type Conversion in Java
🟢 Beginner Level | Java Core Syntax
📖 Definition
Type Casting is the process of converting a variable from one primitive data type to another. Java supports Widening Casting (implicit automatic conversion) and Narrowing Casting (explicit manual casting).
🌐 Multilingual Explanations
English
Widening casting converts smaller to larger data types automatically. Narrowing casting converts larger to smaller data types manually using (type) and can cause data truncation/overflow.
Hindi
Chote data type se bade data type mein automatic widening casting hoti hai. Bade se chote type mein manually narrowing casting `(int)` karni padti hai.
Marathi
Lahan type kadun mothya type kade automatic Widening casting hote. Mothya type kadun lahan type kade Narrowing casting saathi manual `(int)` vapra.
Hinglish
Widening = Safe automatic conversion (e.g., `int` -> `double`). Narrowing = Risky manual conversion with potential data loss (e.g., `(int) 9.99` becomes `9`).
📈 Type Conversion Hierarchy
Widening (Automatic): byte ──► short ──► char ──► int ──► long ──► float ──► double
Narrowing (Manual): double ──► float ──► long ──► int ──► char ──► short ──► byte
⚡ Code Example
public class TypeCastingDemo {
public static void main(String[] args) {
// 1. Widening Casting (Implicit)
int myInt = 9;
double myDouble = myInt; // Automatic casting: 9.0
// 2. Narrowing Casting (Explicit)
double pi = 3.14159;
int intPi = (int) pi; // Manual casting: 3 (decimal truncated)
// 3. ASCII Char to Int Conversion
char letter = 'A';
int asciiValue = letter; // Automatic conversion: 65
System.out.println("intPi: " + intPi + ", ASCII: " + asciiValue);
}
}
⚠️ Common Pitfalls
Integer Truncation & Overflow: Narrowing a float/double to an integer discards all decimal precision without rounding. Casting a number larger than `byte` max (127) to a `byte` causes binary wrap-around overflow.
🎯 Tiered Practice Exercises
- Beginner: Cast a double value
99.99to an integer and print the result. - Intermediate: Demonstrate character arithmetic by adding 1 to
'A'and printing the resulting character. - Advanced: Explain what happens when a
longvalue exceedingInteger.MAX_VALUEis cast to anint.
🧭 Navigation
← 01. Variables & Primitives | Module Hub | 03. Wrapper Classes →