70.6k views
3 votes
Consider the following code segment.

int x = 10;
int y = 20;
/* missing code */
System.out.print(top / bottom);
Which of the following replacements for /* missing code */ will cause an ArithmeticException to occur?
I. int top = x - y;int bottom = y - x;
II. int top = 2 * x;int bottom = y - top;
III. int top = x + y;int bottom = 2 * top;
A. I only
B. II only
C. III only
D. I and II
E. II and III

1 Answer

2 votes

Final answer:

Option II is the only replacement that will cause an ArithmeticException due to division by zero. The other options do not produce a zero in the denominator, and hence no exception occurs.

Step-by-step explanation:

The question relates to a code segment that can potentially throw an ArithmeticException, which typically occurs when there is an illegal operation such as dividing by zero. We're replacing the missing code in the given Java code snippet to determine which option will cause this exception.

Option I: int top = x - y; int bottom = y - x; This will result in top being -10 and bottom being 10, thus no exception will occur as the division is valid.

Option II: int top = 2 * x; int bottom = y - top; With x being 10, top equals 20, and thus bottom equals 0 (20 - 20). This will cause an ArithmeticException because dividing by zero is an illegal operation in Java.

Option III: int top = x + y; int bottom = 2 * top; The value of bottom will be a positive number, hence no exception will occur.

Therefore, the correct answer is B. II only because only option II leads to a division by zero.

User Bill Bell
by
8.2k points

Related questions