Java的‘+’的性质
‘+’在Java中既可以是加法运算也可以是连接符,如何分辨不同的用法呢?关键在于有无String
class StringTest {
public static void main(String[] args) {
char c = 'a';
int num = 10;
String str = "hell0";
System.out.println(c + num + str);
System.out.println(c + str + num);
System.out.println(c + (num + str));
System.out.println((c + num) + str);
System.out.println(str + num + c);
}
}
首先Java的运算是从左到右依次计算,如果有括号的话就先算括号中的部分
——————————我是一条分割线————————————
第一条
System.out.println(c + num + str);
输出的结果是c先与num运算,运算结果再与str运算
- c为char类型 num为int类型 二者相加要发生自动类型提升,即二者的和会为int类型,a的ASCII码为97,与num相加后成为107,那么(c+num)则为107,107为int类型。
- 107再与str进行运算,因为str为字符串,此时‘+’为连接符,将二者拼接起来,得到107hello
第二条
System.out.println(c + str + num);
- c与str进行运算,出现字符串则意味着‘+’代表连接符,故结果为ahello,仍为字符串
- ahello与num运算,即字符串与int,故仍为连接,结果为ahello10
第三条
这里加上了括号,即运算有了新的优先级
System.out.println(c + (num + str));
- 先算括号中的,出现字符串即为连接符,容易得到10hello
- c与10hello连接,得a10hello
第四五条同理,关键在于两两计算时,只要出现字符串类型,‘+’就为连接符
运行结果如下:
巩固加深一下,试试看下面哪个代码能够输出"* *"
System.out.println('*' + '\t' + '*');
System.out.println('*' + "\t" + '*');
System.out.println('*' + '\t' + "*");
System.out.println('*' + ('\t' + "*"));