英文:
Does Java implicitly convert int to String when using the "+" operator on int + String operation?
问题
我有以下代码:
System.out.println("12" + 34); // 输出 "1234"
System.out.println(1 + 2 + "34"); // 输出 "334"
我本以为会出现错误,但实际上,我的整数值被连接到字符串中而没有出错。
有人能详细地解释一下上面发生了什么吗?
-
当Java注意到在一个"+"操作中同时有int和String数据类型时,是否会隐式地将int转换为String类型?
-
为什么在使用+运算符时没有抛出由于错误数据类型而引发的错误?
-
如果确实存在隐式转换,为什么Java会这样做而不抛出错误?
英文:
I have the following code:
System.out.println("12" + 34); // prints "1234"
System.out.println(1 + 2 + "34"); // prints "334"
I was expecting an error, instead, my int values got concatenated to the String without error.
Can someone explain in detail what goes on above?
-
Does Java implicitly convert int to String type when it notices an int AND String data type in a "+" operation?
-
Why isn't there an error thrown due to wrong data types when using the + operator?
-
If there were indeed implicit conversion going on, why does Java do that and not throw an error?
答案1
得分: 2
这个答案解释了你的第二个示例:
System.out.println(1 + 2 + "34"); // 输出 "334"
这里发生的是,表达式 1 + 2
首先发生,这是由于 +
运算符的从左到右的优先级。实际上,任何运算符在相同优先级的情况下都是从左到右的优先级。因此,首先 1 + 2
计算为整数相加得到 3
,然后得到:
System.out.println(3 + "34"); // 输出 "334"
接下来,3 + "34"
被计算为字符串连接,类似于你的第一个示例,输出 "334"
。
英文:
This answer addresses your second example:
System.out.println(1 + 2 + "34"); // prints "334"
What is happening here is that the expression 1 + 2
is happening first, due to the left-to-right precedence of the +
operator. Actually, any operator has left to right precedence all other things being of the same precedence. So, first 1 + 2
evaluates as integer addition to 3
, leaving us with:
System.out.println(3 + "34"); // prints "334"
Next, 3 + "34"
evaluates as string concatenation, similar to your first example, printing "334"
.
答案2
得分: 0
这是Java的拼接操作,请参考以下链接:
> https://stackoverflow.com/questions/12028779/concatenating-string-and-numbers-java
英文:
It is java concatenate. please refer the link.
> https://stackoverflow.com/questions/12028779/concatenating-string-and-numbers-java
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论