Casting and Range of Variables
Big idea: A cast converts a value to another type. Casting to int chops off the decimal part. Numbers also have limits: ints can overflow, and doubles can be slightly off.
- Develop code to cast primitive values to different primitive types in arithmetic expressions and determine the value that is produced as a result.
- Describe conditions when an integer expression evaluates to a value out of range.
- Describe conditions that limit accuracy of expressions.
Casting between int and double
Write the type in parentheses before a value: (int) or (double). A cast applies only to the value right after it, so where you put it matters.
Going from int to double happens automatically when needed (widening): double d = 5; stores 5.0. Going from double to int needs an explicit cast, because information can be lost.
int sum = 7;
int count = 2;
System.out.println(sum / count);
System.out.println((double) sum / count);
System.out.println((double) (sum / count));
System.out.println((int) 8.99);
System.out.println((int) -8.99);Output3 3.5 3.0 8 -8
Rounding to the nearest integer
Casting truncates toward zero; it never rounds. To round, add 0.5 first for non-negative values, or subtract 0.5 for negative values.
Codedouble a = 8.6;
double b = -8.6;
System.out.println((int) (a + 0.5));
System.out.println((int) (b - 0.5));Output9 -9
Integer overflow
An int uses 4 bytes, so it can only hold values from Integer.MIN_VALUE (−2147483648) to Integer.MAX_VALUE (2147483647). Going past either end is overflow: no error happens, but the value wraps around to the other end.
int big = Integer.MAX_VALUE;
System.out.println(big);
System.out.println(big + 1);Output2147483647 -2147483648
Round-off error in doubles
A double stores a close approximation of most decimal values, so arithmetic can be a tiny bit off. That's why you should compare doubles by checking whether they are close (Math.abs(a - b) < 0.000001) rather than with ==, and why exact counts belong in int.
System.out.println(0.1 + 0.2);
System.out.println(0.1 + 0.2 == 0.3);
System.out.println(Math.abs((0.1 + 0.2) - 0.3) < 0.000001);Output0.30000000000000004 false true
(int)truncates toward zero:(int) 3.99is3,(int) -3.99is-3.(double) a / bcastsafirst, so the division is real.(double) (a / b)casts after the int division already lost the fraction.- Round with
(int) (x + 0.5)for x ≥ 0 and(int) (x - 0.5)for x < 0. intvalues outsideInteger.MIN_VALUE..Integer.MAX_VALUEoverflow and wrap around.doublevalues can have round-off error.
int x = 3.0;does not compile. A double never goes into an int without a cast.(int) Math.random() * 10casts onlyMath.random(), which is always 0.
- When you see a cast, put brackets in your head around exactly what it applies to before evaluating.
double avg = (double) (9 / 2);Show answer
Show answer
- Special decimal types such as BigDecimal.