2014 Practice Exam MCQ
First full AP style practice exam.
Question 4: What is printed as a result of executing the code segment?
int x = 7;
int y = 3;
if ((x < 10) && (y < 0))
System.out.println("Value is: " + x * y);
else
System.out.println("Value is: " + x / y);
The answer that I put was 2.3333333...
Since 7/3's true value is that. However, since 7 and 3 are both integers, floating point divison does not occur. Instead, integer division occurs, which means that the number is rounded to 2. The output in the above cell confirms this.
Thus, the output is not
Value is: 2.3333333
But is instead:
Value is: 2
Alternative lesson in casting for this. Here, we will start x and y as floats, and expect division to yield another float. Then we will cast to int to round to nearest whole number.
float x = 7;
float y = 3;
if ((x < 10) && (y < 0))
System.out.println("Value is: " + x * y);
else
System.out.println("Value is: " + x / y);
float x = 7;
float y = 3;
if ((x < 10) && (y < 0))
System.out.println("Value is: " + x * y);
else
System.out.println("Value is: " + (int) (x / y)) ;