[英]Char arithmetic - difference between unary ++ and + 1
What is the difference between using the short forms and the long forms in Java? 在Java中使用短格式和长格式有什么区别? Look at the following code:
看下面的代码:
char myChar = 'p';
myChar += 2;
myChar++;
myChar = myChar + 2;
System.out.println(myChar);
Line 2 and 3 work like expected. 2号线和3号线工作正常。 Line 4 gives the error:
第4行给出了错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to char
I thought line 2 and 4 are the same. 我认为第2行和第4行相同。 But the seem to be not the same?
但是好像不一样吗?
In the unary forms it's implicit that the operand's type is unchanged. 在一元形式中,隐含的是操作数的类型不变。
In the binary form, the addition of the integer 2
causes the type of the whole expression myChar + 2
to be promoted to int
, causing the assignment back to the char myChar
to fail. 在二进制形式中,整数
2
的加法导致整个表达式myChar + 2
的类型提升为int
,从而导致分配回char myChar
操作失败。
For 对于
myChar += 2;
From JLS 15.26.2 : 从JLS 15.26.2开始 :
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
形式为E1 op = E2的复合赋值表达式等效于E1 =(T)((E1)op(E2)),其中T是E1的类型,只是E1仅被评估一次。
So, it is equivalent to: 因此,它等效于:
myChar = (char) (myChar + 2);
As for 至于
myChar = myChar + 2;
myChar
is promoted to int
and added to 2
. myChar
提升为int
并添加到2
。 Now you are assigning this value which is an int
to char
which results in the error. 现在,您正在为
char
分配一个int
值,这会导致错误。
A compound assignment expression of the form E1 op= E2
is equivalent to E1 = (T)((E1) op (E2))
, where T is the type of E1, except that E1 is evaluated only once. 形式为
E1 op= E2
的复合赋值表达式等效于E1 = (T)((E1) op (E2))
,其中T是E1的类型,只是E1仅被评估一次。
The statement myChar+ = 2;
语句
myChar+ = 2;
will be implictly converted into myChar =(char) (myChar + 2);
将隐式转换为
myChar =(char) (myChar + 2);
This is due to automatic promotion. 这是由于自动升级。
int+char will result to int
int+double will result to double
Now if you try to 现在,如果您尝试
int +char ---> store to char
int +double ---> store to int
this will cause an error. 这将导致错误。
but if you try 但是如果你尝试
char c='a';
c++;
it is equal to 它等于
char c = 'a';
c = (char)(c+1);
instead if you use 相反,如果您使用
char c = 'a';
c = c+2;//error
because it is 因为它是
char + int ---> store to char(explained above)//error
hence for writing c = c+2;
因此对于写
c = c+2;
use c = (char)(c+2);
使用
c = (char)(c+2);
now this works as follows..... 现在,它的工作如下.....
c+2; is basically (char + int) so the result is int(& not char)
when you do (char)(c+2);
当你做
(char)(c+2);
the int value is converted to char
Note 注意
The limit of char in java is from 0 to 65535. So if the result of java中char的限制是从0到65535。因此,如果
(char)(char + int)---> store to char
overflows the value then you get unexpected output. 值溢出,您将得到意外的输出。
for example 例如
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.