在字符串操作中,如果表达式以一个字符串起头,那么后续所有操作数都必须是字符串型
public class StringOperators {
public static void main(String[] args) {
int x=0,y=1,z=2;
String s="x+y+z";
System.out.println(s+x+y+z);
System.out.println(x+""+s); //convert x to string
s+="(summed)="; //Concatenation operator
System.out.println(s+(x+y+z));
System.out.println(""+x);
}
}
输出结果如下:
x+y+z012
0x+y+z
x+y+z(summed)=3
0
在结果中,第三行结果和第一行结果之所以不一样,是因为()的优先级比较高,在编译器执行的时候,优先执行()里面的,然后在利用+和前面的S字符串进行拼接,而第一行的结果是由于s是字符串,在拼接的时候,会将X,Y,X转换成他们的字符串形式,然后连接这些字符串,而不是先把他们加在一起。