programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Unary operators - possible lossy conversion

Greenhorn
Posts: 15
Can you pl. help me on the following question:

Test.java:9: error: incompatible types: possible lossy conversion from int to short
s = s + 1;
^

My question:  Expected this error in line 2 and 3.  But error shows only in line 4. Why is 's' treated as 'int' in line 2 and 3?  Any information on this helps.  Thanks in advance.

Bartender
Posts: 572
9
s is not treated as an int on that line. But the token "1" is treated as an int, so s is promoted to an int, the sum is made using ints, and the result is converted back to a short. When an int is converted to a short, it is considered a possible lossy conversion.

Marshal
Posts: 56610
172
So, don't use shorts for arithmetic.

Preethi Chilukuri
Greenhorn
Posts: 15
Fred Kleinschmidt wrote:s is not treated as an int on that line. But the token "1" is treated as an int, so s is promoted to an int, the sum is made using ints, and the result is converted back to a short. When an int is converted to a short, it is considered a possible lossy conversion.

Thank you for your response Fred.

s +=10; -----> line 2

My interpretation was the above line should be considered as s = s+10.  Why s is not considered as int -- as it is being added to int 10?

Greenhorn
Posts: 1
actually here the main problem is type conversion:
s+1 will get int and by doing
s=s+1;
you are assigning int to short which is wrong

author
Sheriff
Posts: 23295
125
Preethi Chilukuri wrote:
s +=10; -----> line 2

My interpretation was the above line should be considered as s = s+10.  Why s is not considered as int -- as it is being added to int 10?

First.... from the Java Language Specification, regarding the compound assignment operations... https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2

So... that line is actually considered as s = (short) (s + 10).

Henry

Campbell Ritchie
Marshal
Posts: 56610
172
. . . and it is possible to get strange results because of that implicit cast.