英文:
How are println and printf different in Jshell
问题
为什么在 JShell 中,println 和 printf 显示不同?
我最近了解了一些关于 JShell 的内容,想尝试一些东西,然后我遇到了这个情况。
为什么 println 的输出是普通输出,而 printf 的输出却包含了那么多内容?
英文:
Why are println and printf displayed differently in Jshell??
I recently found out about JShell stuff and wanted to try a few things and I came across this.
Why is output for println a plain output and output for printf all those stuff??
答案1
得分: 1
printf 返回一个 PrintStream,所以 jshell 正在显示将返回值转换为字符串的结果($1 和 $2 之后的内容),之所以以那种方式显示,是因为 PrintStream 没有覆盖 toString 方法,所以它使用的是 来自 Object 的方法。
正如 Rogue 在评论中指出的,由于 printf 除非被指示,否则不会打印换行符,所以你会在与打印值相同的行上看到返回值。
println 不返回任何内容,所以只会显示打印出来的值(和一个换行符)。
英文:
printf returns a PrintStream, so jshell is showing you that returned value converted to a string (the stuff after $1 and $2), which is shown that way because PrintStream doesn't override toString so it uses the one from Object.
As pointed out by Rogue in the comments, since printf doesn't print a newline unless instructed to, you see the return value on the same line as the printed value.
println returns nothing, so you're only shown the printed value (and a newline).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论