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";
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.
The Java double keyword is a primitive data type. It is a double-precision 64-bit IEEE 754 floating point. It is used to declare the variables and methods. It generally represents the decimal numbers.
format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale. getDefault() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With