Formatting using printf and format
Asked Answered
P

3

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

Pimple answered 25/12, 2011 at 14:20 Comment(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.Wretch
B
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

Buell answered 25/12, 2011 at 14:30 Comment(1)
Yeah, so if you are C developer, be careful, because String.format("%b", 0) and String.format("%b", 1) will both return "true"Spokane
F
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".

Flatling answered 25/12, 2011 at 14:24 Comment(0)
M
0

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

Magness answered 25/12, 2011 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.