-1

I'm learning java and creating some simple test programs with notes in them and I'm getting an error saying "incompatible types: possible lossy conversion from int to short" with short shortVal= val5 + val6; I'm looked and this error meaning I'm trying to put an int value into a short variable but the value I'm storing in the short is only 27, so I'm a bit confused as to what is wrong.

public class test{
    public static void main(String[] args){
        double val1=4;
        float val2=9;
        long val3=30;
        int val4= 8;
        short val5= 15;
        short val6=12;
        byte val7=20;
        short shortVal= val5 + val6; //why the error here?
    }
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
Brandon
  • 1,099
  • 1
  • 9
  • 14
  • 1
    More exact duplicate: http://stackoverflow.com/questions/5919423/why-am-i-getting-a-warning-about-possible-loss-of-precision-in-java – T.J. Crowder Feb 12 '17 at 10:05
  • http://stackoverflow.com/questions/477750/primitive-type-short-casting-in-java – shmosel Feb 12 '17 at 10:06
  • Please [**search thoroughly**](/search?q=%5Bjava%5D+incompatible+types%3A+possible+lossy+conversion+from+int+to+short) before posting. More on searching [here](/help/searching). – T.J. Crowder Feb 12 '17 at 10:07

2 Answers2

1

The result of short + short is, somewhat paradoxically, int. So you're trying to assign an int to a short variable (shortVal).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

short + short will result in an int. You need an int variable to store the result :

int shortVal = val5 + val6;
Jarvis
  • 8,494
  • 3
  • 27
  • 58