Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Largest Java Short (32767) plus 1 not turning negative?

recently I learned about the two's compliment method of representing both positive and negative integers in the base two system. I then tried to see this in action using java with the following short code:

int a=2147483647;
System.out.println("a: "+a);
System.out.println("a+1: "+(a+1));
short b=32767;
System.out.println("b: "+b);
System.out.println("b+1: "+(b+1));

Which outputs:

a: 2147483647

a+1: -2147483648

b: 32767

b+1: 32768

Which confuses me because I would think that b+1, being represented in binary as 011111111111111, would turn into 1000000000000000, or in decimal, -32768. What's going on?

like image 778
Brown Philip Avatar asked Mar 08 '17 21:03

Brown Philip


1 Answers

Although b is a short, the expression (b + 1) is an int. The right operand is an int, the left operand is promoted to an int, and the expression is the promoted type of the operands.

From the Java Language Specification, 5.6.2. Binary Numeric Promotion:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

Note that this last promotion occurs even if both operands are of short type. You can't avoid promotion to an int with (b + (short) 1).

From 15.18.2. Additive Operators (+ and -) for Numeric Types

The type of an additive expression on numeric operands is the promoted type of its operands.

like image 149
Andy Thomas Avatar answered Sep 18 '22 10:09

Andy Thomas