nerdexam
Oracle

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…

Working with Java Data Types

Question

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?

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)
  • A
    5% (2)
  • B
    11% (4)
  • C
    3% (1)
  • D
    82% (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 x by y - it only uses y*100, so the result is 6.0, completely unrelated to the x/y ratio.
  • B uses (int)x/y, which performs integer division (7/6 = 1), then 1/2 is also integer division yielding 0, so z = 0.0.
  • C rounds 1.1666... to the nearest integer (1) before any scaling, so it loses all decimal precision and gives 1.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

#type casting#Math.round()#operator precedence#float arithmetic

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice