我刚从高中的AP Comp sci开始,我偶然发现了一个关于字符串中+操作符的问题
为什么System.out.println ("number" + 6 + 4 * 5)
会导致number620
鉴于
String s = "crunch";
int a = 3, b = 1;
System.out.print(s + a + b);
System.out.print(b + a + s);
crunch314crunch
结果
谢谢
发布于 2013-09-12 06:53:53
依赖于它的优先顺序
当两个操作符共享一个操作数时,优先级较高的操作符优先。例如,1+2*3被视为1+ (2 * 3),而1*2+3被视为(1 * 2) +3,因为乘法比加法 (+)具有更高的优先级。
发布于 2013-09-12 06:53:50
如果您想在System.out.println
中执行任何数学操作,请用大括号包装它,因为Java在第一位看到字符串。
试试System.out.println ("number" + (6 + 4 * 5))
。
第二个示例使用:System.out.print(s + (a + b));
在本例中,您有a
和b
之和。
但在System.out.print(b + a + s);
,b
和a
则是第一名。编译器第一次执行a+b
,在添加字符串之后,不需要大括号
发布于 2013-09-12 06:55:12
"*“具有比"+”更高的运算符优先级,这意味着表达式"4 * 5“是在字符串连接发生之前计算的。
请参阅http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
https://stackoverflow.com/questions/18757312
复制相似问题