Common Errors with Datatypes
1. Loss of Precision
When converting from a larger data type to a smaller one (like double → int or float → int), some part of the data may be lost. This usually happens when decimals are truncated during conversion.
Example:
public class PrecisionLoss {
public static void main(String[] args) {
double value = 12.99;
int num = (int) value; // Explicit casting (double → int)
System.out.println("Original value: " + value);
System.out.println("After conversion: " + num);
}
}
Output:
Original value: 12.99
After conversion: 12
Explanation:
- Only the integer part is kept, while the fractional part (.99) is lost.
- This is called loss of precision.
2. Overflow and Underflow
When a variable stores a value beyond its range, it causes overflow (too large) or underflow (too small). Java does not throw an error but instead wraps around to the other end of the range.
Example:
public class OverflowExample {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
int result = max + 1; // Overflow
System.out.println("Max value: " + max);
System.out.println("After overflow: " + result);
}
}
Output:
Max value: 2147483647
After overflow: -2147483648
Explanation:
- Since int can store only up to 2147483647, adding 1 makes it overflow and wrap to the negative side.
3. NullPointerException
This occurs when you try to access a method or property of an object that is null (i.e., not initialized). It’s a common error when working with non-primitive (reference) types.
Example:
public class NullPointerError {
public static void main(String[] args) {
String text = null;
System.out.println(text.length()); // Error: NullPointerException
}
}
Explanation:
- The variable text does not point to any object in memory.
- Calling length() on null causes a NullPointerException.
Always check for null before using an object:
if (text != null) {
System.out.println(text.length());
}
Summary:
| Error Type | Cause | Example |
|---|---|---|
| Loss of Precision | Converting larger → smaller datatype | double → int |
| Overflow / Underflow | Value goes beyond range | Integer.MAX_VALUE + 1 |
| NullPointerException | Accessing methods on null reference | text.length() |