Unit 1.5: Casting and Range of Variables
AP Computer Science A
Topics Covered:
- Casting primitive values
- Integer overflow conditions
- Accuracy limitations in expressions
- Memory allocation for data types
Learning Objectives
1.5.A
Develop code to cast primitive values to different primitive types in arithmetic expressions and determine the value that is produced as a result.
1.5.B
Describe conditions when an integer expression evaluates to a value out of range.
1.5.C
Describe conditions that limit accuracy of expressions.
Casting Operators
Essential Knowledge 1.5.A.1
The casting operators (int) and (double) can be used to convert from a double value to an int value (or vice versa).
Double to Int
Int to Double
Truncation vs Rounding
Essential Knowledge 1.5.A.2
Casting a double value to an int value causes the digits to the right of the decimal point to be truncated.
Truncation Examples
Essential Knowledge 1.5.A.4
Values of type double can be rounded to the nearest integer by:
- (int)(x + 0.5) for non-negative numbers
- (int)(x - 0.5) for negative numbers
Automatic Casting (Widening)
Essential Knowledge 1.5.A.3
Some code causes int values to be automatically cast (widened) to double values.
When Automatic Casting Occurs
Wrong Way
Right Way
Integer Range and Overflow
Essential Knowledge 1.5.B.1 & 1.5.B.2
Integer values are stored using 4 bytes of memory and must be in the range:
- Integer.MIN_VALUE to Integer.MAX_VALUE
- Approximately -2.1 billion to +2.1 billion
Essential Knowledge 1.5.B.3
If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. The result is an int value in the allowed range but not necessarily the value expected.
Overflow Example
Double Precision and Rounding Errors
Essential Knowledge 1.5.C.1
Computers allot a specified amount of memory to store data based on the data type. If an expression would evaluate to a double that is more precise than can be stored in the allotted amount of memory, a round-off error occurs.
Precision Limitations
Summary
Casting
- Use (int) and (double) to convert
- double → int truncates decimals
- int → double adds .0
- Automatic widening occurs in mixed operations
Range & Precision
- int: ±2.1 billion range
- Overflow wraps around
- double has precision limits
- Use int when exact values matter
Quick Practice
What will this code output?
Answer: 2.0 (integer division happens first, then cast to double)