所以我在这里有此代码:
char a = '1';
char b = '2';
System.out.println(a+b); \\ Outputs 99
我想知道为什么,因为此代码:
char a = '1' + '2';
System.out.println(a); \\ Outputs c
我想增强我的原始思维,请帮助有同情心的人。
如果您运行以下代码
class Example {
public static void main(String[] args) {
char ch = '1';
char ch2 = '2';
int num = ch;
int num2 = ch2;
System.out.println("ASCII value of char " + ch + " is: " + num);
System.out.println("ASCII value of char " + ch2 + " is: " + num2);
}
}
您将看到每个字符的输出是
字符1的ASCII值为:49
char 2的ASCII值为:50
因此,当您执行此System.out.println(a+b);
时,它们将作为整数值相加,结果为99
字符具有实数;当你写
char a = 49;
char k = '1'; // both of them holds same character because '1' code in ascii 49
并且当您在算术运算中处理两个变量,并且如果其中一个类型为(byte,short或char)时,这些类型会以int形式提升,因此>]
System.out.println(a+b); // both of them promote int
char c = a + b; // assign c, 99 which represents 'c'