Java OCA OCP Practice Question 2414

Question

Given the following variables, which options will throw exceptions at runtime?

String s = "Guru";
Integer start = 100;
boolean win = true;
Float duration = new Float(-1099.9999);
  • a System.out.format("%d", s);
  • b System.out.printf("%s", start);
  • c System.out.printf("[%-12b]", win);
  • d System.out.format("%s12", s);
  • e System.out.format("%d", duration);
  • f System.out.format("[%+,-(20f]", duration);


a, e

Note

You'll get runtime exceptions if you use either of the following for a format specifier:.

An invalid data type
An invalid combination of flags

Options (a) and (e) throw runtime exceptions because they use the format specifier %d, which must be used only with integer literal values or variables, and not with String or decimal numbers.

Option (b) won't throw any exception because you can pass any type of primitive variable or object reference to the format specifier %s.

Also, this option doesn't use any format flag that's invalid to be used with %s.

Option (c) won't throw any exceptions.

You can specify the alignment and width element -12 with %b.

Option (d) won't throw any exceptions.

The value 12 that follows %s is not part of the width element, but a literal value following %s, so it's a completely valid format string.




PreviousNext

Related