java char 加减法_关于java:Char算术 – 一元++和+ 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行是相同的。 但似乎不一样了?

在情况1和2中,存在从int到char的隐式转换。 如果查看字节代码,您将看到i2c指令。 情况3,您必须将其显式转换为char。

java?中的+ = 10和a = a + 10之间的差异,Java + =运算符

在一元形式中,隐含的是操作数的类型不变。

在二进制形式中,添加整数2会导致整个表达式myChar + 2的类型被提升为int,从而导致返回char myChar失败。

那么...... myChar = myChar + (char)2?

不 - 它将是myChar = (char)(myChar + 2)

根据@thegauravmahawar现在删除的答案的引用,myChar += 2不等于myChar = myChar + 2,而是等于myChar = (char) (myChar + (char) 2))(来源)。

另外 - myChar = myChar + (char)2不起作用 - 你会得到"可能的精度损失"错误。

对于

myChar += 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.

所以,它相当于:

myChar = (char) (myChar + 2);

至于

myChar = myChar + 2;

myChar被提升为int并添加到2。现在您要将此值int分配给char,这会导致错误。

这是由于自动推广。

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.

形式E1 op= E2的复合赋值表达式等效于E1 = (T)((E1) op (E2)),其中T是E1的类型,但E1仅计算一次。

语句myChar+ = 2;将被隐含地转换为myChar =(char) (myChar + 2);

不,它不会 - 它会被隐式转换为(char)(myChar + 2) - 不完全相同的东西

是的Alnitak我忘了那一个。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值