1Z0-819 · Question #158
public class Tester { public static void main(String[] args) { byte x = 7, y = 6; // Line 1 System.out.println(z); } } Which expression when added at Line 1 will produce the output of 1.17?
The correct answer is D. float z = (float)Math.round((float)x/y*100)/100. Option D correctly produces 1.17 by following the right order of operations: (float)x/y yields 1.1666..., multiplying by 100 gives 116.666..., Math.round() produces 117 (a long), and finally casting to float before dividing by 100 gives 1.17. The key is that the cast to float…
Question
Options
- Afloat z = (float)(Math.round((int)y*100)/100);
- Bfloat z = Math.round((int)x/y)/2;
- Cfloat z = Math.round((float)x/y);
- Dfloat z = (float)Math.round((float)x/y*100)/100;
How the community answered
(38 responses)- A5% (2)
- B11% (4)
- C3% (1)
- D82% (31)
Explanation
Option D correctly produces 1.17 by following the right order of operations: (float)x/y yields 1.1666..., multiplying by 100 gives 116.666..., Math.round() produces 117 (a long), and finally casting to float before dividing by 100 gives 1.17. The key is that the cast to float happens before the final division, preventing integer division from truncating the result.
Why the distractors fail:
- A never divides
xbyy- it only usesy*100, so the result is6.0, completely unrelated to thex/yratio. - B uses
(int)x/y, which performs integer division (7/6 = 1), then1/2is also integer division yielding0, soz = 0.0. - C rounds
1.1666...to the nearest integer (1) before any scaling, so it loses all decimal precision and gives1.0.
Memory tip: Think "Scale → Round → Unscale." To round to 2 decimal places, multiply by 100 first, round to a whole number, then cast to float and divide by 100. If you divide first without the float cast, Java's integer division silently discards everything after the decimal point.
Topics
Community Discussion
No community discussion yet for this question.