• Post Reply Bookmark Topic Watch Topic
  • New Topic

Unary operators - possible lossy conversion  RSS feed

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you pl. help me on the following question:



Received the following error:
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, don't use shorts for arithmetic.
 
Preethi Chilukuri
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
so please  make it correct
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and it is possible to get strange results because of that implicit cast.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!