DATA LOSS IN JAVA
Type Conversion & Narrowing Casting
What is Data Loss?
In Java, data loss occurs during Narrowing Type Casting. This happens
when you manually convert a larger primitive data type into a smaller
data type.
Since the smaller type has less memory (bits), it cannot hold the full
value of the larger type, leading to truncated or corrupted values.
Types of Data Loss
1. Truncation (Decimal Loss)
When converting a floating-point number (double or float) to an
integer type (int, long), the fractional part is simply discarded.
double myDouble = 9.99;
int myInt = (int) myDouble;
// Result: 9 (The .99 is LOST)
2. Out-of-Range (Overflow/Wrap-around)
When the value exceeds the maximum capacity of the target type, Java
performs a "wrap-around" based on 2's complement logic.
int largeInt = 130;
byte myByte = (byte) largeInt;
// byte range is -128 to 127.
// Result: -126 (Data is corrupted/wrapped)
The Hierarchy (Direction of Loss)
Direction Type Data Loss?
Small → Large Widening (Automatic) NO
Large → Small Narrowing (Manual) YES (POSSIBLE)
double > float > long > int > char > short > byte
CRITICAL NOTE: Java does not give a compile-time error for data loss
during manual casting. It is the programmer's responsibility to
ensure the value fits in the target type!
Example Summary
• Magnitude Loss: long (64-bit) to int (32-bit).
• Precision Loss: float (32-bit) to long (64-bit). (Even though long is
bigger, it can't store decimals).
Java Programming Concept Series - Data Integrity