簡體   English   中英

字符運算-一元++和+ 1之間的區別

[英]Char arithmetic - difference between unary ++ and + 1

在Java中使用短格式和長格式有什么區別? 看下面的代碼:

char myChar = 'p';
myChar += 2;
myChar++;
myChar = myChar + 2;        
System.out.println(myChar);

2號線和3號線工作正常。 第4行給出了錯誤:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
        Type mismatch: cannot convert from int to char

我認為第2行和第4行相同。 但是好像不一樣嗎?

在一元形式中,隱含的是操作數的類型不變。

在二進制形式中,整數2的加法導致整個表達式myChar + 2的類型提升為int ,從而導致分配回char myChar操作失敗。

對於

myChar += 2;

JLS 15.26.2開始

形式為E1 op = E2的復合賦值表達式等效於E1 =(T)((E1)op(E2)),其中T是E1的類型,只是E1僅被評估一次。

因此,它等效於:

myChar = (char) (myChar + 2);

至於

myChar = myChar + 2;

myChar提升為int並添加到2 現在,您正在為char分配一個int值,這會導致錯誤。

形式為E1 op= E2的復合賦值表達式等效於E1 = (T)((E1) op (E2)) ,其中T是E1的類型,只是E1僅被評估一次。

語句myChar+ = 2; 將隱式轉換為myChar =(char) (myChar + 2);

這是由於自動升級。

int+char will result to int
int+double will result to double

現在,如果您嘗試

int +char ---> store to char
int +double ---> store to int

這將導致錯誤。


但是如果你嘗試

char c='a';
c++;

它等於

char c = 'a';
c = (char)(c+1);

相反,如果您使用

char c = 'a';
c = c+2;//error

因為它是

char + int ---> store to char(explained above)//error

因此對於寫c = c+2; 使用c = (char)(c+2); 現在,它的工作如下.....

c+2; is basically (char + int) so the result is int(& not char)

當你做(char)(c+2); the int value is converted to char


注意

java中char的限制是從0到65535。因此,如果

(char)(char + int)---> store to char

值溢出,您將得到意外的輸出。

例如

char c  = (char)65535;//valid
c++; will result as c = 0 (not 65536) due to the limit of char.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM