Adding 2 numbers of type short in Java


So, the type short is 16 bits, from -32768 to 32767.

Simple code:

short x1 = 5, x2 = 38;
x1 = x1 + x2;
System.out.println(x1);

Swears at an error in line 2, asks to lead to the type int:

Uncompilable source code - incompatible types: possible lossy conversion from int to short

Although it would seem why-the addition of two numbers of the same type.

But this code, oddly enough, works without errors:

short x1 = 5, x2 = 38;
x1 += x2;
System.out.println(x1);

Output: 43

Why?

Author: Denis, 2016-12-28

2 answers

Any arithmetic operations on the short type yield int (the result is automatically cast to int). In the case of x1 += x2, in fact, x1 = (short) (x1 + x2)

When evaluating the expression (a @ b) the arguments a and b are converted to numbers of the same type:

  • if one of the numbers is double, then in double
  • otherwise, if one of the numbers float, then in float
  • otherwise, if one of the numbers is long, then in long
  • otherwise, both numbers are converted to int

That is, all integer literals in expressions, as well as types byte, short and char expand to int.

 21
Author: V. Makhnutin, 2016-12-28 13:17:07

According to the Java SE 8 Edition specification (15.26.2 Compound Assignment Operators)

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.

That is, there is an explicit conversion of the type of the right expression to the type of the left expression

E1 = (T) ((E1) op (E2))
    ^^^^

For your example, this sentence is

x1 += x2;

Equivalent according to quote the following sentence

x1 = ( short )( x1 + x2 );

For a non-compound assignment operator, there is no such explicit type conversion, so you should use explicit type conversion yourself, if required, and in this example

short x1 = 5, x2 = 38;
x1 = x1 + x2;

Since the type of the expression x1 + x2 is int and the left operand is of type short, that is, there is a "narrowing" of the value, then you should write

short x1 = 5, x2 = 38;
x1 = ( short )( x1 + x2 );

I think it will be important to note for expanding your horizons that the same rule applies This is also the case in C#. That is, with respect to this operation, Java and C# behave the same way. This code is

short x1 = 5, x2 = 38;
x1 = x1 + x2;

It will also not compile in C#, whereas this code

short x1 = 5, x2 = 38;
x1 += x2;

It compiles successfully, since it is possible to explicitly convert from type int to type short.

 9
Author: Vlad from Moscow, 2016-12-28 14:15:44