Search code examples
javacertificatenumber-formattingscjp

SCJP - number format


Given:

public class LineUp {
    public static void main(String[] args) {
        double d = 12.345;
        // insert code here
    }
}

Which code fragment, inserted at line 4, produces the output | 12.345|?

A. System.out.printf("|%7d| \n", d);
B. System.out.printf("|%7f| \n", d);
C. System.out.printf("|%3.7d| \n", d);
D. System.out.printf("|%3.7f| \n", d);
E. System.out.printf("|%7.3d| \n", d);
F. System.out.printf("|%7.3f| \n", d);
Answer: F

What is the interpretation of the printf statements , why is the |%7d| is giving illegalFormatConversionException ?

Thanks


Solution

  • Because d is a double and it can't be formatted as a decimal integer.You can't use the "d" format descriptor in case of floating-point variables, without an explicit cast in order to signal the fact that you are aware of the possible loss of precision.