Negative char JAVA value

Why is this happening as follows:

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

Result 65535

Why don't they get a compilation error or runtime exception? I expected this to not be negative. Instead, he starts the countdown upside down. Thanks in advance.

+5
source share
2 answers

Why don't they get a compilation error or runtime exception?

Since the language specification means that arithmetic for primitive types is modular 2^width, therefore -1it becomes 2^16-1like char.

The whole operations section indicates that

Integer integer operators do not indicate overflow or underflow.

to prohibit throwing an exception.

postfix-, , 15.14.3

1 , . (§5.6.2) 1 . (. 5.1.3) / (. 5.1.7) . - .

: 1 int ( char), -1 int, :

T , n , n - , T. , , .

char 0xFFFF ( Java , ):

. Java , , int long . , . x, -x (~ x) +1.

:

, , . , , , .

, a - b == a + (-b) , .

+15

Java. (, , ). .

+1

All Articles