34

In the following program

class ZiggyTest2 {

    public static void main(String[] args){     

        double x = 123.456;
        char c = 65;
        int i = 65;

        System.out.printf("%s",x);
        System.out.printf("%b",x);
        System.out.printf("%c",c);
        System.out.printf("%5.0f",x);
        System.out.printf("%d",i);
    }       
}

The output is

123.456trueA  12365

Can someone please explain how a double value (i.e. 123.456) is converted to a boolean (ie. true)

The reason I ask is because I know java does not allow numbers to be used for boolean values. For example, the following is not allowed in Java

if (5) {
 //do something
}

Thanks

Jagger
  • 10,350
  • 9
  • 51
  • 93
ziggy
  • 15,677
  • 67
  • 194
  • 287
  • 1
    I think it's nice to point out that there is an important difference between the use of booleans in `if` statements versus in `printf`. That is, an `if` statement requires a primitive `boolean` (or a `Boolean` object, which will be unboxed). So any non-boolean value is not allowed. However, `printf` requires its arguments to be of type `Object`, i.e. any type. So, the compiler does not put any restrictions on the arguments to `printf`: even if they are primitive types like `boolean`, they can be boxed (to `Boolean`). This is why you can pass unexpected types to `printf` but not to `if`. – Resigned June 2023 Jun 04 '16 at 02:41

3 Answers3

99

for "%b" : If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".

reference

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
  • 4
    Yeah, so if you are C developer, be careful, because String.format("%b", 0) and String.format("%b", 1) will both return "true" – Sheng.W Nov 09 '15 at 09:01
10

The API documentation seems to clearly state why.

If the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".

Janath
  • 137
  • 9
Kal
  • 24,724
  • 7
  • 65
  • 65
0

Because the value is of type double and this is how the %b converter works with values of this type.

Jagger
  • 10,350
  • 9
  • 51
  • 93