java - 负字符值JAVA

标签 java char int

为什么会出现以下情况:

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

结果65535

为什么不给出编译错误或运行时异常? 我预计它是因为字符不能为负数。相反,它从颠倒开始倒数。 提前致谢。

最佳答案

Why does not give it out a compilation error or a runtime Exception?

因为语言规范要求基元类型的算术运算以 2^width 为模,因此 -1 变为 2^16-1 作为 char

the section on integer operations ,据说

The built-in integer operators do not indicate overflow or underflow in any way.

这样就禁止抛出异常。

对于所使用的后缀自减运算符,具体而言,其行为在 15.14.3 中指定。

Otherwise, the value 1 is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable before the new value is stored.

二进制数字提升将值和 1 都转换为 int(因为这里的类型是 char),因此中间结果 -1 作为 int,然后执行缩小基元转换:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

生成 char 值为 0xFFFF(因为 Java 为其有符号整数类型指定了二进制补码表示形式, unary minus 规范中明确说明):

For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.

对于超出范围结果的一般环绕行为,例如 in the specification of the multiplication operator :

If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.

类似的短语出现在整数加法的规范中,并且需要减法来满足a - b == a + (-b),因此溢出行为如下。

关于java - 负字符值JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46397235/

相关文章:

java - Scala.List 和 Java.util.List 之间的互操作

java - 使用 SimpleMailMessage() 发送邮件时 Spring 中的 NullPointerException

c - c中逐个字符的结构成员

c++ - 如果我们向它输入一个整数,那么一个字符会给出整数作为输出,但是当一个整数被分配给它时,这不会发生。为什么?

java - 向 java.util.Calendar 添加真实的天数(不是一年中的天数)

C++多行输入

java - 字符串到整数的转换

java - 如何用 ' ' 声明 int?为什么 '2' == 50?

c - 从文本文件读取C中不同类型的变量

java - Java类错误