java int 和 string 的类型转换
上次考试我们进行了确定以下代码的输出的练习:
System.out.println(2 + 3 + ">=" + 1 + 1);
我的答案是 5 >= 2
但现在我意识到这是错误的答案。它应该是5 >= 11
。 但为什么?
last exam we had the exercise to determine the output of the following code:
System.out.println(2 + 3 + ">=" + 1 + 1);
My answer was 5 >= 2
but now I realize that this is the wrong answer. It should be 5 >= 11
.
But why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您的语法是:
表达式从左到右求值,在本例中 2 + 3 求和为 5,并且当“添加”到字符串时结果为
"5 >="
,当添加到 1 得到"5 >= 1"
,再添加 1,结果为:"5 >= 11"
Assuming that your syntax is :
expressions are evaluated from left to right, in this case 2 + 3 get summed to 5 and when "added" to a string result in
"5 >="
, which when added to 1 gives"5 >= 1"
, add another 1 and your result is:"5 >= 11"
因为将字符串“添加”到任何内容都会导致串联。以下是它在编译阶段的评估方式:
编译器将进行常量折叠,因此编译器实际上可以一次缩减表达式一部分,并替换为常量表达式。然而,即使它不这样做,运行时路径实际上也是相同的。就这样:
您可以通过用括号分隔第二个数字加法表达式来强制整数加法。例如:
Because "adding" a string to anything results in concatenation. Here is how it gets evaluated in the compilation phase:
The compiler will do constant folding, so the compiler can actually reduce the expression one piece at a time, and substitute in a constant expression. However, even if it did not do this, the runtime path would be effectively the same. So here you go:
You can force integer addition by sectioning off the second numeric addition expression with parentheses. For example:
它是从左到右评估的。您将
"1"
连接到"5 >=
,最后将"1"
连接到"5 >= 1"< /代码>。
It is evaluated from left to right. You concatenate
"1"
to"5 >="
and finally"1"
to"5 >= 1"
.让我们从左到右一次读取一个标记:
遇到的第一个文字是一个整数
2
,然后是一个+
,然后是另一个整数3< /代码>。两个整数之间的
+
是加法,因此它们相加为5
。现在我们有
5
,一个整数,然后是一个+
,然后是一个字符串">="
。整数和字符串之间的+
是连接运算符。因此,字符串组合起来形成"5>="
。然后我们有
"5>="
、一个字符串、一个+
,然后是一个整数1
。这又是字符串连接。所以结果是“5>=1”
。最后我们有
"5>=1"
、一个字符串、一个+
和一个1
。他又是字符串连接。所以结果是“5>=11”
。Let's read it one token at a time from left to right:
The first literal encountered is an integer,
2
, then a+
, then another integer,3
. A+
between two integers is addition, so they are added together to be5
.Now we have
5
, an integer, then a+
, then a String">="
. A+
between an integer and a String is a concatenation operator. So the Strings are combined to form"5>="
.Then we have
"5>="
, a String, a+
, and then an integer,1
. This is String concatenation again. So the result is"5>=1"
.Finally we have
"5>=1"
, a String, a+
, and the a1
. his is String concatenation again. So the result is"5>=11"
.