我想要的效果是121,但下面这个出来的结果是61;分开写(注释掉的部分),答案会是121.
想问一下这个61是怎么出来的,它的运算逻辑是什么?
public class draft {
public static void main(String[] args) {
String str = "";
str += 12 + '1';
// str += 12;
// str += '1';
System.out.println(str);
}
}
str += 12,会将12视为字符串
str += 12 + '1';会先执行 12+'1',会将两个数当作整数计算。字符'1'的ASCII码是49,加上12是61,str+=61,将61当作字符,所以最终输出61
'1'是char类型,与int类型相加会使用其ASSIC码值进行运算,其ASSIC码值应该是49,所以12 + '1' = 61
str += 12 + '1';是会先进行12 + '1'的运算求得61再与str相加运算得到字符串61
要想直接得到121可以写成 str += 12 + "1";