AP Computer Science a Quiz: Casting And Range Of Variables
16 questions · exam conditions
0:00
Casting And Range Of VariablesQuestion 1 of 16

A physics renderer stores pixels in a short:

class MotionRenderer {
  public static short packPixels(int pixels) {
    return (short) pixels; // narrowing conversion
  }
}

Considering the given scenario, what error will occur if the value of pixels exceeds its type range?

The short result wraps, producing an incorrect value.
Java throws a runtime exception for narrowing casts.
The value becomes 0 because of underflow in integers.
The cast is ignored and pixels stays an int.
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Casting And Range Of Variables

Practice Casting And Range Of Variables in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on Casting And Range Of Variables, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

All questions

Question 1

A physics renderer stores pixels in a short:

class MotionRenderer {
  public static short packPixels(int pixels) {
    return (short) pixels; // narrowing conversion
  }
}

Considering the given scenario, what error will occur if the value of pixels exceeds its type range?

  1. The short result wraps, producing an incorrect value. (correct answer)
  2. Java throws a runtime exception for narrowing casts.
  3. The value becomes 0 because of underflow in integers.
  4. The cast is ignored and pixels stays an int.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how narrowing conversions to smaller integer types can cause overflow. A short can only hold values from -32,768 to 32,767, so casting larger int values causes the result to wrap around within this range, producing incorrect values. In the provided scenario, casting from int to short when pixels exceeds short's range results in wraparound, as shown in the packPixels method's narrowing conversion. Choice A is correct because it accurately describes that the short result wraps when the int value exceeds short's range, producing an incorrect value. Choice B is incorrect because Java doesn't throw runtime exceptions for narrowing casts between primitive types - overflow occurs silently. To help students: Demonstrate wraparound with examples like casting 40,000 to short and showing the negative result. Practice calculating wrapped values using modulo arithmetic and emphasize the importance of range checking before narrowing conversions.

Question 2

A physics simulation sends pixels to a graphics API:

class MotionRenderer {
  public static int toPixels(double meters) {
    double pixels = meters * 100.0;
    return (int) pixels; // truncation for API compatibility
  }
}

Based on the code above, what will be the result of casting the variable pixels from double to int?

  1. It rounds up to the next integer automatically.
  2. It becomes an int by truncating any fractional part. (correct answer)
  3. It keeps fractional pixels but stores them as int.
  4. It causes a compile-time error due to incompatibility.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how truncation affects coordinate calculations in graphics programming. Graphics APIs typically require integer pixel coordinates, necessitating conversion from floating-point calculations, which inherently loses precision through truncation. In the provided scenario, casting from double to int results in truncation of any fractional pixel values, as shown when (int) pixels removes the decimal portion of the calculated pixel position. Choice B is correct because it accurately describes that casting to int truncates the fractional part, which is standard Java behavior for narrowing conversions. Choice A is incorrect because it suggests automatic rounding up, when Java actually truncates toward zero regardless of the fractional value. To help students: Demonstrate with visual examples how 150.8 pixels becomes 150, potentially affecting rendering precision. Practice identifying when precision loss matters (like in graphics) versus when it's acceptable, and discuss alternative approaches like Math.round() when rounding is desired.

Question 3

In a game, bonuses are doubles but score is int:

class ScoreKeeper {
  public static int applyBonus(int score, double bonus) {
    int total = score + (int) bonus; // truncates decimals
    return total;
  }
}

Based on the code above, what will be the result of casting the variable bonus from double to int?

  1. It rounds bonus to the nearest integer before adding.
  2. It truncates bonus's fractional part before adding. (correct answer)
  3. It permanently changes bonus to type int in memory.
  4. It causes a compile-time error because double cannot be cast.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how casting from double to int affects numeric values. Casting from a floating-point type to an integer type truncates (removes) the fractional part rather than rounding to the nearest integer. In the provided scenario, casting bonus from double to int results in the removal of any decimal portion, as shown in the code comment '// truncates decimals'. Choice B is correct because it accurately describes that casting truncates the fractional part before adding, ensuring students understand that Java's type conversion doesn't round but simply drops decimal values. Choice A is incorrect because it reflects a common misconception that casting performs rounding, which occurs when students confuse casting with Math.round() functionality. To help students: Emphasize that casting to int always truncates toward zero, never rounds. Practice with examples like (int)3.9 = 3 and (int)-3.9 = -3 to reinforce this behavior.

Question 4

A game stores score as int and adds a large bonus:

class ScoreTracker {
  public static int addHugeBonus(int score) {
    int bonus = 50;
    int result = score + Integer.MAX_VALUE; // range risk
    return result;
  }
}

Considering the given scenario, which line of code will cause a problem due to range limitations?

  1. int bonus = 50;
  2. int result = score + Integer.MAX_VALUE; (correct answer)
  3. return result;
  4. public static int addHugeBonus(int score) {

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how integer overflow occurs when exceeding type limits. Integer types have fixed ranges, and attempting to store values beyond these ranges causes overflow, where the value wraps around to the opposite end of the range. In the provided scenario, adding Integer.MAX_VALUE to any positive score will cause overflow because the result exceeds the maximum value an int can hold, as shown in the line with score + Integer.MAX_VALUE. Choice B is correct because it identifies the exact line where overflow occurs - adding Integer.MAX_VALUE to a positive score will always exceed int's range. Choice A is incorrect because declaring a simple int with value 50 poses no range risk. To help students: Demonstrate overflow with concrete examples showing how Integer.MAX_VALUE + 1 becomes Integer.MIN_VALUE. Use debugging tools to trace variable values and show the wraparound effect when overflow occurs.

Question 5

A game casts a large double into an int score:

class ScoreTracker {
  public static int unsafeCast(double totalScore) {
    return (int) totalScore; // may exceed int range
  }
}

Considering the given scenario, what error will occur if the value of totalScore exceeds its type range?

  1. A compile-time error prevents the cast from compiling.
  2. The int result overflows and wraps to an incorrect value. (correct answer)
  3. Java automatically clamps it to Integer.MAX_VALUE.
  4. The value becomes null because it cannot fit in int.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how casting large values can cause overflow without warning. When a double value exceeds Integer.MAX_VALUE or is less than Integer.MIN_VALUE, casting to int doesn't throw an exception but instead produces an incorrect wrapped value. In the provided scenario, casting from double to int when totalScore exceeds int's range results in overflow and wraparound, as shown in the unsafeCast method. Choice B is correct because it accurately describes that the int result overflows and wraps to an incorrect value, which is Java's behavior for narrowing primitive conversions. Choice A is incorrect because Java allows casting from double to int at compile time - the overflow happens at runtime without exceptions. To help students: Demonstrate overflow with concrete examples like casting 3 billion (double) to int and showing the negative result. Practice identifying scenarios where range checking is necessary before casting and introduce defensive programming techniques.

Question 6

A game adds a large bonus to an int score:

class ScoreKeeper {
  public static int addHugeBonus(int score) {
    double bonus = 3_000_000_000.0;
    int total = score + (int) bonus; // may overflow int
    return total;
  }
}

Which line of code will cause a problem due to range limitations?

  1. Line double bonus = 3_000_000_000.0;
  2. Line int total = score + (int) bonus; (correct answer)
  3. Line return total;
  4. No line; int can store any positive whole number.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how integer overflow occurs when values exceed type limits. The int data type in Java has a maximum value of 2,147,483,647 (approximately 2.1 billion), while the bonus value of 3 billion exceeds this range. In the provided scenario, casting 3_000_000_000.0 from double to int results in integer overflow on line 'int total = score + (int) bonus;', causing unexpected negative values due to wraparound. Choice B is correct because it accurately identifies where the range limitation problem occurs - when the large double value is cast to int, exceeding int's maximum capacity. Choice D is incorrect because it reflects a common misconception that int can store any positive whole number, which occurs when students don't understand that primitive types have fixed size limits. To help students: Emphasize memorizing key type ranges (int: ±2.1 billion, long: ±9.2 quintillion). Practice identifying potential overflow scenarios and use long when dealing with large whole numbers.

Question 7

A banking method computes interest using mixed types:

class BankAccount {
  public static double computeInterest(int balance, float rate) {
    int years = 3;
    return balance * rate * years; // int promoted to float/double
  }
}

Based on the code above, what will be the result of casting the variable balance from int to double?

  1. It becomes a double with the same numeric value. (correct answer)
  2. It truncates digits because doubles store fewer bits.
  3. It changes balance to double permanently after return.
  4. It causes overflow because doubles have smaller range.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how numeric promotion works in mixed-type arithmetic expressions. When performing arithmetic with mixed numeric types, Java automatically promotes smaller types to larger ones to prevent precision loss, with int being promoted to float or double as needed. In the provided scenario, the int balance is automatically promoted to match the floating-point type in the expression, resulting in a double with the same numeric value, as shown in the multiplication expression. Choice A is correct because it accurately describes that the int becomes a double with the same numeric value through automatic promotion. Choice D is incorrect because it reflects a misconception about type ranges - doubles actually have a much larger range than ints, not smaller. To help students: Create examples showing automatic promotion in expressions like int * float. Emphasize the promotion hierarchy (byte→short→int→long→float→double) and explain how Java prevents precision loss through widening conversions.

Question 8

A game adds a double bonus to an int score:

class ScoreTracker {
  public static int addBonus(int score, double bonus) {
    score += (int) bonus; // cast before adding
    return score;
  }
}

Considering the given scenario, how can the casting from double to int affect the calculation?

  1. It truncates the bonus, possibly reducing the added points. (correct answer)
  2. It increases bonus precision by keeping all decimals.
  3. It converts score into a double for the rest of the program.
  4. It prevents overflow because int becomes a wider type.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how casting before arithmetic operations affects the final result. When a double is cast to int before being added to another int, any fractional portion of the bonus is lost through truncation, potentially reducing the player's reward. In the provided scenario, casting bonus from double to int before addition results in truncation of decimal points, as shown when (int) bonus removes fractional values before the addition operation. Choice A is correct because it accurately identifies that truncation reduces the bonus by removing fractional points, possibly giving players less than intended. Choice C is incorrect because it misunderstands variable scope and type - the cast only affects the bonus value in the expression, not the score variable's type. To help students: Compare outcomes of score + (int)bonus versus (int)(score + bonus) to show order of operations matters. Emphasize the importance of understanding when casting occurs in complex expressions and how parentheses can change results.

Question 9

A game stores score as int and adds a huge bonus:

class ScoreKeeper {
  public static int addHugeBonus(int score) {
    double bonus = 3.0e9; // very large
    int total = score + (int) bonus; // potential overflow
    return total;
  }
}

Based on the code above, which line of code will cause a problem due to range limitations?

  1. Line double bonus = 3.0e9;
  2. Line int total = score + (int) bonus; (correct answer)
  3. Line return total;
  4. Line public static int addHugeBonus(int score)

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how integer overflow occurs when casting large double values to int. The int data type in Java has a maximum value of approximately 2.1 billion (2312^31 - 1), while double can represent much larger values, creating potential overflow situations during casting. In the provided scenario, casting from double to int in line int total = score + (int) bonus; causes a problem because 3.0e9 (3 billion) exceeds the maximum int value, resulting in integer overflow. Choice B is correct because it identifies the exact line where the large double value is cast to int, causing overflow that wraps the value to a negative number due to two's complement representation. Choice A is incorrect because declaring a large double value itself causes no problems - the issue only occurs during the cast to int. To help students: Emphasize the importance of checking value ranges before casting between types with different capacities. Practice identifying scenarios where overflow might occur and use long or BigInteger for very large values when needed.

Question 10

A game clamps score after adding a bonus:

class ScoreKeeper {
  public static int safeAdd(int score, double bonus) {
    int added = (int) bonus; // may be large
    int total = score + added; // overflow risk
    return total;
  }
}

Which line of code will cause a problem due to range limitations?

  1. Line int added = (int) bonus;
  2. Line int total = score + added; (correct answer)
  3. Line return total;
  4. Line public static int safeAdd(int score, double bonus)

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically identifying where integer overflow can occur in multi-step calculations. While casting double to int might truncate values, the real overflow risk occurs when adding two integers that together exceed int's maximum value. In the provided scenario, the overflow risk is on line 'int total = score + added;' where two int values are added, potentially exceeding Integer.MAX_VALUE, as indicated by the comment '// overflow risk'. Choice B is correct because it accurately identifies where range limitations cause problems - during integer addition rather than during the cast operation itself. Choice A is incorrect because while casting may truncate, it doesn't cause overflow - the truncated value will always fit in an int. To help students: Emphasize that overflow can occur in any integer arithmetic operation, not just during casting. Practice identifying all potential overflow points in code, especially in accumulator patterns where values grow through addition.

Question 11

A physics simulation converts a large distance to pixels:

class Renderer {
  public static int toPixels(double meters) {
    double pixelsExact = meters * 1_000_000.0;
    int pixels = (int) pixelsExact; // may exceed int max
    return pixels;
  }
}

What error will occur if the value of pixelsExact exceeds its type range when stored in pixels?

  1. A compile-time error stops the program from compiling.
  2. An automatic exception is always thrown at runtime.
  3. Overflow wraps the int value to an unexpected number. (correct answer)
  4. Underflow occurs because ints cannot represent positives.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how integer overflow behaves in Java when casting from larger types. When a double value exceeds Integer.MAX_VALUE (2,147,483,647), casting to int doesn't throw an exception but instead wraps around to negative values. In the provided scenario, casting pixelsExact from double to int when it exceeds int's maximum range results in overflow wrap-around, as indicated by the comment '// may exceed int max'. Choice C is correct because it accurately describes that overflow wraps the int value to an unexpected (typically negative) number, ensuring students understand Java's silent overflow behavior. Choice A is incorrect because it reflects a common misconception that overflow causes compile-time errors, which occurs when students expect Java to catch all potential errors at compile time. To help students: Emphasize that Java doesn't throw exceptions for integer overflow - it silently wraps around. Practice calculating overflow results using modular arithmetic to predict wrapped values.

Question 12

A physics simulation passes pixel positions to a graphics API:

class Motion {
  public static int toPixels(double meters, double scale) {
    double px = meters * scale;
    return (int) px; // graphics needs int pixels
  }
}

Considering the given scenario, how can the casting from double to int affect the calculation?

  1. It truncates fractional pixels, reducing smooth motion. (correct answer)
  2. It preserves all decimals, improving smooth motion.
  3. It makes px store larger values than before.
  4. It changes meters to an int permanently.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how precision loss affects graphics rendering when converting from double to int coordinates. Graphics APIs typically require integer pixel positions, but physics simulations often calculate positions with floating-point precision for accuracy, creating a necessary but potentially problematic conversion. In the provided scenario, casting from double to int truncates fractional pixel values, which can result in jerky or non-smooth motion as sub-pixel movements are lost. Choice A is correct because it accurately describes how truncation reduces smooth motion by discarding fractional pixel positions, ensuring students understand the trade-off between calculation precision and display requirements. Choice B is incorrect because it reflects a misconception that casting preserves decimal information, which occurs when students don't understand that int types cannot represent fractional values. To help students: Emphasize the importance of understanding API requirements and the implications of type conversions. Practice with animation examples to visualize how truncation affects movement smoothness, and discuss techniques like anti-aliasing that address these issues.

Question 13

A game clamps score but still risks overflow:

class ScoreKeeper {
  public static int riskyAdd(int score, double bonus) {
    int add = (int) bonus;
    int total = score + add; // may overflow int
    return total;
  }
}

Based on the code above, what error will occur if the value of total exceeds its type range?

  1. Java throws a runtime overflow exception.
  2. The value wraps around due to integer overflow. (correct answer)
  3. The program fails to compile immediately.
  4. total becomes null until it fits the range.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how integer overflow behaves in Java when the sum exceeds int's maximum value. Java does not throw exceptions for integer overflow; instead, it uses two's complement arithmetic where values wrap around from positive to negative, which can cause unexpected program behavior. In the provided scenario, if score + add exceeds Integer.MAX_VALUE (approximately 2.1 billion), the result wraps around to a negative value, creating a logical error in the score calculation. Choice B is correct because it accurately describes that integer overflow causes value wrapping rather than an exception, ensuring students understand Java's silent overflow behavior. Choice A is incorrect because it reflects a misconception that Java throws overflow exceptions like some other languages, which occurs when students assume all errors result in exceptions. To help students: Emphasize that integer overflow is silent in Java and programmers must explicitly check for it. Practice with examples showing how MAX_VALUE + 1 becomes MIN_VALUE to reinforce the wraparound concept.

Question 14

A game converts a large double bonus into an int:

class ScoreKeeper {
  public static int castBonus(double bonus) {
    int add = (int) bonus; // may exceed int range
    return add;
  }
}

Based on the code above, what error will occur if the value of bonus exceeds its type range when cast?

  1. A compile-time error prevents the cast.
  2. The cast clamps add to Integer.MAX_VALUE.
  3. The resulting int is out of range and becomes an overflowed value. (correct answer)
  4. Java throws a checked exception during casting.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically what happens when casting a double value that exceeds int's range. Unlike some languages, Java does not clamp values or throw exceptions during primitive type casting; instead, it performs a narrowing conversion that can produce unexpected results. In the provided scenario, casting a double larger than Integer.MAX_VALUE to int results in an overflow where the lower 32 bits of the double's binary representation are interpreted as an int, often producing a seemingly random negative or positive value. Choice C is correct because it accurately describes that the cast produces an overflowed value rather than clamping or throwing an exception, ensuring students understand Java's casting behavior. Choice B is incorrect because it reflects a misconception that Java automatically clamps values during casting, which occurs when students assume protective behavior that doesn't exist. To help students: Emphasize that casting between primitive types in Java is a bit-level operation without range checking. Practice with specific examples showing how large doubles cast to unexpected int values to reinforce this behavior.

Question 15

An e-commerce app totals prices as floats:

class Cart {
  public static int checkoutCents(float priceA, float priceB) {
    float total = priceA + priceB;
    int cents = (int) (total * 100); // rounding/truncation risk
    return cents;
  }
}

How can the casting from float to int affect the calculation?

  1. It may drop fractional cents, producing a smaller total. (correct answer)
  2. It guarantees exact cents because floats store decimals exactly.
  3. It changes total's type to int, so later math is integer-only.
  4. It uses brackets like [int] to convert, so results vary.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how floating-point imprecision combined with casting affects e-commerce calculations. Float arithmetic can introduce small errors, and when multiplied by 100 and cast to int, these errors can result in incorrect cent values. In the provided scenario, casting (total * 100) from float to int may drop fractional cents due to both floating-point imprecision and truncation, as noted in the comment '// rounding/truncation risk'. Choice A is correct because it accurately describes that fractional cents may be dropped, producing a smaller total, which is critical for accurate financial transactions. Choice B is incorrect because it reflects a common misconception that floats store decimals exactly, which occurs when students don't understand floating-point representation limitations. To help students: Emphasize that financial calculations should avoid float/double when exact decimal precision is required. Practice using BigDecimal or integer cents for monetary calculations to avoid precision issues.

Question 16

An e-commerce cart converts price to cents:

class Cart {
  public static int toCents(float price) {
    int cents = (int) (price * 100); // truncation risk
    return cents;
  }
}

Based on the code above, what will be the result of casting the variable (price * 100) from float to int?

  1. It truncates any fractional cents after multiplication. (correct answer)
  2. It rounds to the nearest cent automatically.
  3. It converts using string formatting, not casting.
  4. It changes price itself into an int permanently.

Explanation: This question tests AP Computer Science A skills in understanding casting and range of variables, specifically how order of operations affects casting results in calculations. When converting prices to cents, multiplying by 100 first creates a float result that may have fractional cents due to floating-point arithmetic imprecision. In the provided scenario, casting (price * 100) from float to int results in truncation of any fractional cents that might exist after multiplication, as noted in the comment '// truncation risk'. Choice A is correct because it accurately describes that casting truncates any fractional cents after multiplication, ensuring students understand that even seemingly whole numbers in float can have tiny fractional parts. Choice B is incorrect because it reflects a common misconception that casting performs rounding, which occurs when students assume type conversion includes mathematical rounding operations. To help students: Emphasize that floating-point multiplication can introduce small fractional errors. Practice examining edge cases like 19.99 * 100 = 1998.9999... in float arithmetic.