Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8039390

Unexpected behaviour of String.format with null arguments

XMLWordPrintable

    • b79
    • Verified

        j.l.String.format specification says about passing null as format argument: "The behaviour on a null argument depends on the conversion". Conversions described in j.u.Formatter specification. According to this specification only "general" conversions ("%s", "%b" and "%h") may be applied to null argument. If another conversion have been applied to null, method should throw NullPointerException according to j.l.String spec ("Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown").
        Current String.format realization handles null for all conversions the same way, printing "null" (as specification says to do for "%s" and "%h" only).

        Considering compatibility it would be appropriate to change specification and add the discription of this behaviour for all conversions. Or method implementation should be fixed.

        String.format specification: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...)
        Formatter specification:
        http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

        Minimized test:
        ---------------------------------------------------------------------------------------------------------------------------------
        public static void main(String[] args) {
                String[] formats = { "%c", "%d", "%o", "%x", "%e", "%f", "%g", "%tc" };
                for (String format : formats)
                    System.out.print(String.format(format, null));
            }
        ---------------------------------------------------------------------------------------------------------------------------------
        Output:
        nullnullnullnullnullnullnullnull

              sherman Xueming Shen
              slukyanov Stanislav Lukyanov (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              6 Start watching this issue

                Created:
                Updated:
                Resolved: