Type converstion
Introduction
Java is a strongly typed language, which means every variable has a fixed data type.
Sometimes, we need to convert one data type into another—this process is called type conversion or type casting.
Understanding type conversion is very important because wrong casting can lead to overflow and unexpected results.
What is Type Conversion?
Type conversion is the process of converting:
- one primitive data type into another primitive data type
Example:
int→doubledouble→intint→byte
Why Type Conversion Exists
Type conversion is needed because:
Different data types occupy different memory sizes
Arithmetic operations require compatible data types
Java wants to prevent unsafe assignments
Precision and performance must be balanced
Types of Type Conversion in Java
Java supports two main types:
1. Widening Type Conversion (Implicit)
2. Narrowing Type Conversion (Explicit)
1. Widening Type Conversion (Implicit Casting)
Definition
Widening conversion happens when:
A smaller data type is converted into a larger data type
Conversion is done automatically by Java
No data loss occurs
Order of Widening
byte → short → int → long → float → double
Example
int x = 50;
double y = x;
Why It Is Safe
Larger data types can store all values of smaller ones
Java allows this without casting
2. Narrowing Type Conversion (Explicit Casting)
Definition
Narrowing conversion happens when:
A larger data type is converted into a smaller data type
Conversion must be done manually
Data loss may occur
Syntax
targetType variable = (targetType) value;
Example
double price = 99.99;
int rounded = (int) price;
📌 Decimal part is removed, not rounded.
What is Overflow in Java?
Overflow occurs when:
A value exceeds the storage capacity of the target data type
Java does not throw an error
Extra bits are discarded
This usually happens during explicit narrowing conversion.
Why Overflow Happens
Each data type has a fixed range:
| Data Type | Range |
| byte | -128 to 127 |
| short | -32,768 to 32,767 |
| int | -2³¹ to 2³¹−1 |
If a value goes beyond this range:
Java keeps only the lower bits
Result may appear incorrect but follows binary rules
Java Uses Two’s Complement
Java stores signed integers using two’s complement representation.
Key points:
Leftmost bit decides sign
Overflow wraps values in a circular manner
Behavior is predictable, not random
Automatic Type Promotion in Expressions
Java applies type promotion during arithmetic operations.
Rule
byte,short, andcharare automatically promoted tointduring arithmetic operations.
Example
byte a = 10;
byte b = 20;
int sum = a + b;
📌 Result is int, not byte.
Why Java Promotes to int
CPU efficiency – int operations are faster
Reduces overflow risk
Consistent arithmetic rules
Simpler compiler design