大家都知道,在java中有一个特殊的String类,其中在String类中使用运算符“+”的时候并不是做加运算,而是连接两个字符串。但是有一点是新手很容易忽视的问题,一不小心就容易出错。
下面举一个例子来说明:
- public class testString{
- public static void main(String[] args){
- int x=2;
- int y=3;
- System.out.println(x+y);
- System.out.println("the sum of x plus y is"+x+y); //注意看这两个输出语句的结果有什么不同?为什么不同?
- }
- }
输出结果为:5
the sum of x plus y is 23
从这个输出语句中大家是不是看出了什么问题,本来也是想输出the sum of x plus y is 5的,但是最后的输出结果不是我们想要的!为什么?来分析一下:大家应该知道表达式求值是从左到右的循序,既然两个加号中的第一个分隔了一个字符串常量和整数变量:
System.out.println("the sum of x plus y is"+x+y);
这个加号被解释成字符串的连接运算符,其结果是产生了中间字符串"the sum of x plus y is 2"。第二个加号分隔了这个中间字符串和整数变量,因此第二个加号也被解释成字符串的连接运算符,最终产生了字符串" the sum of x plus y is 23"。
为了达到我们开始的目的,通过使用括号可以做到;System.out.println("the sum of x plus y is"+(x+y)); 。