Java中+(加号)运算符的优先级是什么? [英] What is the precedence of the + (plus) operator in Java?

查看:67
本文介绍了Java中+(加号)运算符的优先级是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java教程中,加运算符的优先级仅列出一次.优先级表.但是,以下Java表达式:

The precedence for the plus operator is listed only once in the java tutorial precedence table. However the following Java expressions:

String unexpected = "1 + 1 = " + 1 + 1; 
String expected   = "1 + 1 = " + (1 + 1);
System.out.println(unexpected);
System.out.println(expected);

输出结果:

1 + 1 = 11
1 + 1 = 2

这是否意味着加号运算符在用于连接字符串时具有更高的优先级,或者这意味着加号运算符的优先级对于字符串和数字没有什么不同,但是它只是从左到右求值?

Does this mean the plus operator has a higher precedence when used to concatenate Strings, or does it mean the plus operator's precedence is no different for Strings and Numbers, but that it is simply evaluated left to right?

推荐答案

+ 始终从左右流动

在您的第一个示例中, String意外="1 + 1 =" + 1 + 1; ,字符串首先出现,然后是int值,因此将1视为字符串.

in your first example String unexpected = "1 + 1 = " + 1 + 1; , string comes first and then the int value so 1 is treated as string.

在第二个示例中,字符串期望="1 +1 =" +(1 +1); ,您使用的是(),其优先级高于+运算符.( BODMAS )

in your second example String expected = "1 + 1 = " + (1 + 1); , you are using () which is having higher precedence over + operator.(BODMAS)

考虑另一个示例:

String unexpected1 =1+1+ "1 + 1 = " ;
 System.out.println(unexpected1);

输出将为 21 +1 =

这里首先是int值,所以1 + 1 = 2,然后是字符串文字,所以2与1 + 1 =串联

here int value comes first so 1+1 =2 and then the string literal so 2 is concatenated with 1+1=

这篇关于Java中+(加号)运算符的优先级是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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