Summary: Casting and Ranges of Values
Key Concepts
- Type casting is used to convert values from one type to another in Java.
- The cast operators (int) and (double) create temporary values converted to a different data type.
- Casting a double to an int truncates the decimal portion (does not round).
- In expressions with doubles, ints are automatically converted to doubles.
- Rounding doubles to the nearest integer: (int)(x + 0.5) for positive numbers, (int)(x - 0.5) for negative numbers.
- Integer values in Java (int type) have a finite range from Integer.MIN_VALUE to Integer.MAX_VALUE.
- Integer overflow occurs when a value outside the allowed range is assigned to an int, potentially resulting in incorrect values.
Important Formulas
- Casting double to int:
int result = (int) doubleValue;
- Casting int to double:
double result = (double) intValue;
- Rounding positive double to nearest int:
int rounded = (int)(doubleValue + 0.5);
- Rounding negative double to nearest int:
int rounded = (int)(doubleValue - 0.5);
Common Pitfalls
- Forgetting that integer division truncates the result (e.g., 3 / 4 equals 0, not 0.75).
- Not considering potential integer overflow when working with large numbers.
- Confusing truncation (what happens when casting double to int) with rounding.
- Forgetting to cast when necessary, leading to unexpected results in calculations.