Consider the following code segment. What is printed as a result of executing the code segment?
int a = 7;
int b = 2;
double x = a / b;
double y = (double) a / b;
System.out.println(x);
System.out.println(y);
3 followed by 33.0 followed by 3.53.5 followed by 3.54.0 followed by 3.5x print 3.0, while the cast on a makes the second division floating-point.
Explanation
Division uses the operand types present when / is evaluated. In a / b both operands are int, so the fractional part is discarded and the whole-number result is then widened. Casting a first converts one operand before the division.
- A is not correct: both variables are declared as
double, so each printed value carries a fractional part rather than appearing as a whole number. - C is not correct: the first division has two
intoperands, so the fraction is discarded before the result is widened, and a later widening cannot restore it. - D is not correct: casting and widening never round upward; integer division truncates toward zero, so the first statement keeps only the whole-number part.