Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
like image 667
H2ONaCl Avatar asked Oct 03 '13 06:10

H2ONaCl


People also ask

Can double be null in Java?

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.

What is %d and %s in Java?

%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.

What is double format Java?

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.

What does .format do in Java?

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.


1 Answers

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.

like image 67
Jim Garrison Avatar answered Oct 14 '22 04:10

Jim Garrison