Learn AP Comp Sci

Problem of the Day

Problem:

Consider the following code segment.

int a = 7;
int b = 2;
System.out.println(a / b * 1.0 + ", " + b % a);

What is printed as a result of executing the code segment?

  1. 3, 2
  2. 3.0, 2
  3. 3.5, 2
  4. 3.5, 2.0

Show solution:

The correct answer is b. Order of operations for the first calculation, a / b * 1.0, dictates that the integer division a / b (or 7 / 2 be performed first, with a result of 3. Multiplying that value by 1.0 yields 3.0. The second calculation is a modulo function, returning the remainder result of 2 / 7, or 2.