3

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?

Evan
  • 2,441
  • 23
  • 36
  • As a tip `System.out.println( String.format( "%b %b", nullValue, falseValue ) );` can be reduced as `System.out.printf("%b %b%n", nullValue, falseValue ) ;`, `%n` new line – azro Nov 02 '18 at 15:35
  • I disagree that this is a duplicate, the question Jakg linked to is useful, but simply asks what the string format parameter for boolean is, not specifically how to handle getting null output accordingly. – Evan Nov 02 '18 at 15:57
  • `If the argument arg is null, then the result is "false"` is the beginning of the answer, does it seem related to yours now ? – azro Nov 02 '18 at 15:59
  • Related yes, but it doesn't specifically address the best way of getting null, false, or true out of some toString function I'm not seeing as available. Writing my own at this point, but wondering if I'm missing something. – Evan Nov 02 '18 at 16:01
  • You want to write null ? `Boolean a = null; System.out.println(a);` – azro Nov 02 '18 at 16:03
  • This is going into a logger that receives a format string and parameters. I distilled it down specifically to System.println( String.format( ) ) as an SSCE to represent the problem I need to solve. – Evan Nov 02 '18 at 16:05
  • 1
    If you want null, true, false, then just use %s – Mark Rotteveel Nov 02 '18 at 21:08

1 Answers1

6

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.

Jakg
  • 922
  • 12
  • 39