Why am I getting a “Possible loss of precision” warning in Java?

class Test
{
    public static void main(String[] args)
    {
         short s=2,s1=200,s2;
         s2=s+s1; // error: "possible loss of precision"
         System.out.println(s2);
    } 
}

Why is assigning the result of adding two short circuits to a short cause a compilation error?

+3
source share
5 answers

Because when you assign a numeric literal, Integer is used by default. The compiler does not check the value to verify the accuracy, which will not be lost.

In addition, Java will perform integer arithmetic. See The primitive type "short" - casting in Java for more information on short values.

+2
source

Since to perform arithmetic operations with shorts, the compiler first expands them to integers:

S2 = s + s1

In fact

S2 = (int)s +(int)s1

int.

+5

int, int .

:

s2=(short)(s+s1);
+2

, 32,767 < s + s1 s+s1 < -32,768

-32,768 - 32,767 - .

+1

, Java int ; Java - .

It is worth noting a few things:

  • The data type is shortrarely used outside arrays.

  • If the sum includes the variable that you are assigning, you can avoid the need for explicit casting using the operator +=, because all complex arithmetic / assignment operators involve casting the original variable (if necessary).

0
source

All Articles