H2ONaCl
H2ONaCl

Reputation: 11309

Java null Double object formatting

Is this correct behaviour for Java?

public static void main(String[] args) {
    String floatFormat = "%4.2f\n";
    Double d = null;
    String s = String.format("%4f\n" + floatFormat, d, d);
    System.out.print(s);
}

The output:

null
  nu

My workaround is to hardcode the word "null" and that's annoying.

String thing = (d != null) ? String.format(floatFormat, d) : "null\n";

Upvotes: 6

Views: 1603

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

Under the "general" formatting category (which includes %s) in the Javadoc is this:

The precision is the maximum number of characters to be written to the output. The precision is applied before the width, thus the output will be truncated to precision characters even if the width is greater than the precision. If the precision is not specified then there is no explicit limit on the number of characters.

My educated guess is that when the formatter sees the null it switches the f conversion to s since it makes no sense to format the string null as a float. Then it interprets the width and precision in that context. The field width is still 4, but the maximum output length is 2, right justified, giving the result you see.

Later on in the Javadoc is this:

Unless otherwise specified, passing a null argument to any method or constructor in this class will cause a NullPointerException to be thrown.

So I'd say there's a good case for filing a bug with Oracle, as the spec clearly states an NPE is required for your case.

Upvotes: 2

Related Questions