Java OCA OCP Practice Question 2412

Question

What is the output of the following code?

public class Main {
    public static void main(String... args) {
        double num1 = 7.12345678;
        int num2 = (int)8.12345678;
        System.out.printf("num1=%f, num2=%2d, %b", num1, num2, num2);
    }
}
  • a num1=7.123456, num2= 8, true
  • b num1=7.123456, num2=8, true
  • c num1=7.123457, num2= 8, true
  • d num1=7.123457, num2=8 , true
  • e num1=7.1234, num2=8, false
  • f num1=7.1234, num2=8.1234, true
  • g Compilation error
  • h Runtime exception


c

Note

By default, %f prints out six digits after the decimal number.

It also rounds off the last digit.

So num1=%f outputs 7.123457 and not 7.123456.

Because the double literal 8.

12345678 is explicitly casted to an int value, num2 contains the integer part of the double literal 8.12345678, that is, 8.

%2d sets the total width of the output to 2 digits, padded with spaces and right-aligned by default.

It outputs a space preceding the digit 8.

For all non-Boolean primitive values, %b outputs true.




PreviousNext

Related