在字符串文字之后,所有的+都会被视为字符串连接运算符么? [英] After a string literal, all the + will be treated as string concatenation operator why?

查看:105
本文介绍了在字符串文字之后,所有的+都会被视为字符串连接运算符么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有理解为什么在连接中将整数视为字符串文字的原因。例如,

I haven't understood the reason why integer is treated as string literal in concatenation. E.g.

String s=10+30+" Sachin "+40+40;  
System.out.println(s);

输出为: 40 Sachin 4040

为什么 40 + 40 没有添加,为什么 10 + 30 是否已添加?

Why 40+40 is not getting added and why 10+30 is getting added?

推荐答案

表达式从左到右进行评估。前两个操作数都是 int (10和30),因此第一个 + 执行添加。

The expression is evaluated left to right. The first two operands are both int (10 and 30), so the first + performs addition.

下一个 + 获得 int 操作数(40 )和字符串操作数(Sachin),因此它将 int 转换为字符串并执行 String 连接。

The next + gets an int operand (40) and a String operand (" Sachin "), so it converts the int to String and performs String concatenation.

下一个 + 运算符获得 String 操作数和一个 int 操作数,还执行 String 连接。

The next + operators get a String operand and an int operand, and also perform String concatenation.

如果您需要不同的评估订单,请使用括号:

If you want a different evaluation order, use parentheses :

String s=10+30+" Sachin "+(40+40);  

这将输出 40 Sachin 80

这篇关于在字符串文字之后,所有的+都会被视为字符串连接运算符么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆