1.5 Casting and Range of Variables
Suggested Skills: 2.A, 4.A
LO 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.A.1 — The casting operators
(int)and(double)can be used to convert from adoublevalue to anintvalue (or vice versa).1.5.A.2 — Casting a
doublevalue to anintvalue causes the digits to the right of the decimal point to be truncated.1.5.A.3 — Some code causes
intvalues to be automatically cast (widened) todoublevalues.1.5.A.4 — Values of type
doublecan be rounded to the nearest integer by(int)(x + 0.5)for non-negative numbers or(int)(x - 0.5)for negative numbers.
LO 1.5.B — Describe conditions when an integer expression evaluates to a value out of range.
1.5.B.1 — The constant
Integer.MAX_VALUEholds the value of the largest possibleintvalue. The constantInteger.MIN_VALUEholds the value of the smallest possibleintvalue.1.5.B.2 — Integer values in Java are represented by values of type
int, which are stored using a finite amount (4 bytes) of memory. Therefore, anintvalue must be in the range fromInteger.MIN_VALUEtoInteger.MAX_VALUEinclusive.1.5.B.3 — If an expression would evaluate to an
intvalue outside of the allowed range, an integer overflow occurs. The result is anintvalue in the allowed range but not necessarily the value expected.
LO 1.5.C — Describe conditions that limit accuracy of expressions.
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
doublethat is more precise than can be stored in the allotted amount of memory, a round-off error occurs. The result will be rounded to the representable value. To avoid rounding errors that naturally occur, useintvalues.❌ EXCLUSION — Other special decimal data types that can be used to avoid rounding errors are outside scope.
Last updated
Was this helpful?