Java的‘+’的性质

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运算

  1. c为char类型 num为int类型 二者相加要发生自动类型提升,即二者的和会为int类型,a的ASCII码为97,与num相加后成为107,那么(c+num)则为107,107为int类型。
  2. 107再与str进行运算,因为str为字符串,此时‘+’为连接符,将二者拼接起来,得到107hello

第二条

System.out.println(c + str + num);
  1. c与str进行运算,出现字符串则意味着‘+’代表连接符,故结果为ahello,仍为字符串
  2. ahello与num运算,即字符串与int,故仍为连接,结果为ahello10

第三条

这里加上了括号,即运算有了新的优先级

System.out.println(c + (num + str));
  1. 先算括号中的,出现字符串即为连接符,容易得到10hello
  2. c与10hello连接,得a10hello

第四五条同理,关键在于两两计算时,只要出现字符串类型,‘+’就为连接符

运行结果如下:

巩固加深一下,试试看下面哪个代码能够输出"*   *"

System.out.println('*' + '\t' + '*');
System.out.println('*' + "\t" + '*');
System.out.println('*' + '\t' + "*");
System.out.println('*' + ('\t' + "*"));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值