简体   繁体   English

Java中奇怪的printf()行为

[英]strange printf() behavior in Java

I have the following code fragment 我有以下代码片段

System.out.printf("%b\n", 123);

which prints "true". 打印“ true”。

Can somebody explain this behavior? 有人可以解释这种行为吗? shouldn't this throw a IllegalFormatException? 这不应该抛出IllegalFormatException吗?

Well since the specification says: 既然规范说:

"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". " ( src ) “如果参数arg为null,则结果为“ false”。如果arg为布尔值或布尔值,则结果为String.valueOf()返回的字符串。否则,结果为“ true”。“( src

The behavior is quite expected isn't it? 该行为是完全预期的,不是吗? Why they decided to implement it that way - no idea, I'd agree that it's not intuitive (but well it follows C which also prints just anything if you give it the wrong arguments ;) ) 为什么他们决定以这种方式实现它-不知道,我同意它不是直观的(但是很好,它跟在C后面,如果您给它错误的参数,它也会打印出任何内容;))

From the JavaDocs: 从JavaDocs:

If the argument arg is null, then the result is "false". 如果参数arg为null,则结果为“ false”。 If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). 如果arg是布尔值或布尔值,则结果是String.valueOf()返回的字符串。 Otherwise, the result is "true". 否则,结果为“ true”。

The argument you're giving it isn't null , boolean , or Boolean , so it falls under "Otherwise" and therefore is true 您提供的参数不是nullbooleanBoolean ,因此它属于“ Otherwise”,因此为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM