Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting using printf and format

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

like image 647
ziggy Avatar asked Dec 25 '11 14:12

ziggy


People also ask

What is printf () in Java?

The printf function (the name comes from “print formatted”) prints a string on the screen using a “format string” that includes the instructions to mix several strings and produce the final string to be printed on the screen.

What is the difference between printf and format?

The key difference between them is that printf() prints the formatted String into console much like System. out. println() but the format() method returns a formatted string, which you can store or use the way you want.

What is the difference between format and printf in Java?

printf: prints the formatted String into console much like System. out. println() but. format: method return a formatted String, which you can store or use the way you want.


2 Answers

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

like image 52
dku.rajkumar Avatar answered Oct 16 '22 16:10

dku.rajkumar


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".

like image 41
Kal Avatar answered Oct 16 '22 18:10

Kal