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
if
statements versus inprintf
. That is, anif
statement requires a primitiveboolean
(or aBoolean
object, which will be unboxed). So any non-boolean value is not allowed. However,printf
requires its arguments to be of typeObject
, i.e. any type. So, the compiler does not put any restrictions on the arguments toprintf
: even if they are primitive types likeboolean
, they can be boxed (toBoolean
). This is why you can pass unexpected types toprintf
but not toif
. – Wretch