Search code examples
javastring-formatting

Why is the output of Java String.format null Boolean false and how to String.format as null instead?


I'm sure that has been asked before, but I couldn't find the answer.

Boolean nullValue = null;
Boolean falseValue = false;
System.out.println( String.format( "%b %b", nullValue, falseValue ) );

How is the output of this "false false"? That's exactly what I get out on my machine. Java 8. Mac. Java noob.

EDIT

So this is the intended behavior. It doesn't look like Boolean toString produces my desired behavior of outputting null, false, true either. Is everyone who wants this supposed to write a method on their own? Is there function that produces that output?


Solution

  • If you look in the method java.util.Formatter.FormatSpecifier.printBoolean(Object) it only prints "true" if the variable is true - otherwise false is printed.

    Looking further this has been covered in a previous StackOverflow question. This behavior is specified in the documentation.