负字符值JAVA

扫码查看
本文介绍了负字符值JAVA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会发生以下情况:

Why doe it happen the following:

char p = 0;
p--;
System.out.println(p);

结果 65535

为什么不给出编译错误或运行时异常?
我期望它作为字符不能为负。相反,它开始从倒置计数。
提前感谢。

Why does not give it out a compilation error or a runtime Exception?I expected it as chars cannot be negative. Instead it starts back counting from upside down.Thanks in advance.

推荐答案

因为语言规范要求原语类型的算术运算是 code>,因此 -1 变为 2 ^ 16-1

Because the language specification mandates that arithmetic on primitive types is modulo 2^width, so -1 becomes 2^16-1 as a char.

在,表示

,以便禁止抛出异常。

对于所使用的postfix-decrement运算符,具体来说,它的行为在

For the postfix-decrement operator used, specifically, its behaviour is specified in 15.14.3

二进制数字促销转换二者,值和1,到 int (因为这里的类型是 char ),因此你有中间结果 -1 作为 int ,则执行变窄原语转换:

The binary numeric promotion converts both, the value and 1, to int (since the type here is char), thus you have the intermediate result -1 as an int, then the narrowing primitive conversion is performed:

导致 char 的值 0xFFFF (因为Java明确地指定了它的有符号整数类型的二进制补码表示在的说明中说明):

resulting in a char value of 0xFFFF (since Java specifies two's complement representation for its signed integer types, explicitly stated in the specification of unary minus):

作为示例,在乘法运算符的规范中:

For the general wrap-around behaviour for out-of-range results, as an example in the specification of the multiplication operator:

类似的短语出现在整数加法的规范中,需要减法来满足 a - b == a +(-b)

Similar phrases occur in the specification of integer addition, and subtraction is required to fulfill a - b == a + (-b), so the overflow behaviour follows.

这篇关于负字符值JAVA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 04:19
查看更多