Type Casting (Implicit & Explicit)
Type casting in Java is the process of converting one data type into another. It is commonly used when assigning values between variables of different data types. Understanding type casting is crucial to avoid data loss, compilation errors, and runtime bugs, and it is a frequent interview topic.
What Is Type Casting?
- Converting a value from one data type to another
- Mainly applicable to primitive data types
- Can be automatic or manual
Types of Type Casting in Java
Java supports two types of type casting:
- Implicit Type Casting (Widening)
- Explicit Type Casting (Narrowing)
1. Implicit Type Casting (Widening)
What Is Implicit Casting?
- Automatically performed by Java
- Converts smaller data type to larger data type
- No data loss
- Safe conversion
Order of Widening
byte → short → int → long → float → double
char → int → long → float → double
Example
int a = 10;
double b = a; // implicit casting
Why it works: An int fits safely inside a double.
More Examples
byte b = 20;
int i = b;
char ch = 'A';
int ascii = ch;
Why Implicit Casting Matters
- Prevents unnecessary code
- Improves readability
- Safe and compiler-controlled
2. Explicit Type Casting (Narrowing)
What Is Explicit Casting?
- Done manually by the programmer
- Converts larger data type to smaller data type
- Possible data loss
- Requires casting operator
Syntax
targetType variable = (targetType) value;
Example
double d = 10.75;
int i = (int) d;
Output: i = 10 (decimal part lost)
More Examples
int i = 130;
byte b = (byte) i; // overflow
Result: b = -126
Type Casting with char
char ch = 'A';
int x = ch; // implicit
char c = (char) x; // explicit
Data Loss in Explicit Casting
- Decimal truncation
- Overflow or underflow
- Unexpected results
int num = 300;
byte b = (byte) num;
Type Casting Rules (Important)
- Implicit casting → safe
- Explicit casting → programmer responsibility
- boolean cannot be cast to or from any other type
- Casting does not change original variable
Type Casting vs Type Conversion
- Casting → done by programmer
- Conversion → automatic (compiler-driven)
Common Beginner Mistakes
- Assuming explicit casting rounds values
- Ignoring overflow scenarios
- Casting boolean values
- Forgetting parentheses
- Confusing casting with parsing
Interview-Ready Answers
Short Answer
Type casting in Java is converting one data type into another, either implicitly or explicitly.
Detailed Answer
Java supports implicit type casting where smaller data types are automatically converted to larger types, and explicit type casting where larger data types are manually converted to smaller types using casting operators, which may cause data loss.
Key Takeaway
Implicit casting is safe and automatic, while explicit casting is powerful but risky. Always be cautious of data loss and overflow when performing explicit type casting.