Java null formatting a double object

Is this the correct behavior 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); } 

Output:

 null nu 

My workaround is hard coding the word "null" and it is annoying.

 String thing = (d != null) ? String.format(floatFormat, d) : "null\n"; 
+6
source share
1 answer

Under the โ€œgeneralโ€ formatting category (which includes %s ) in Javadoc:

Accuracy is the maximum number of characters that must be written to the output. Accuracy is applied to the width, so the output will be truncated to precision characters, even if the width is greater than the accuracy. If precision is not specified, then there is no explicit character limit.

My educated guess is that when formatter sees zero, it toggles the conversion of f to s , since there is no point in formatting the null string as a float. He then interprets the width and precision in this context. The width of the field is still 4, but the maximum output length is 2, aligned right, giving the result you see.

Later in Javadoc is:

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

So, I would say that there is a good case for submitting errors with Oracle, as the specification clearly states that NPE is required for your business.

+2
source

Source: https://habr.com/ru/post/955165/


All Articles