問題描述
在練習 Java 時,我隨機想到了這個:
While practicing Java I randomly came up with this:
class test
{
public static void main(String arg[])
{
char x='A';
x=x+1;
System.out.println(x);
}
}
我以為它會拋出一個錯誤,因為我們不能將數(shù)值 1
與數(shù)學(xué)中的字母 A
相加,但是下面的程序運行正確并打印
I thought it will throw an error because we can't add the numeric value 1
to the letter A
in mathematics, but the following program runs correctly and prints
B
這怎么可能?
推薦答案
在 Java 中,char
是數(shù)字類型.當您將 1
添加到 char
時,您將進入下一個 unicode 代碼點.如果是 'A'
,下一個代碼點是 'B'
:
In Java, char
is a numeric type. When you add 1
to a char
, you get to the next unicode code point. In case of 'A'
, the next code point is 'B'
:
char x='A';
x+=1;
System.out.println(x);
請注意,您不能使用 x=x+1
,因為它會導(dǎo)致隱式縮小轉(zhuǎn)換.您需要改用 x++
或 x+=1
.
Note that you cannot use x=x+1
because it causes an implicit narrowing conversion. You need to use either x++
or x+=1
instead.
這篇關(guān)于Java中的遞增字符類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!