Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"possible loss of precision" is Java going crazy or I'm missing something?

I'm getting a "loss of precision" error when there should be none, AFAIK.

this is an instance variable:

byte move=0;

this happens in a method of this class:

this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF);

move is a byte, move is still a byte, and the rest is being cast to a byte.

I get this error:

[javac] /Users/looris/Sviluppo/dumdedum/client/src/net/looris/android/toutry/Guy.java:245: possible loss of precision
[javac] found   : int
[javac] required: byte
[javac]             this.move=(this.move<<4)|(byte)(Guy.moven.indexOf("left")&0xF);
[javac]                                         ^

I've tried many variations but I still get the same error.

I'm now clueless.

like image 537
o0'. Avatar asked Nov 30 '22 18:11

o0'.


2 Answers

Actually all logic operatos (& | ^) return an int, regardless of their operands. You have to cast the final result of x|y as well.

like image 76
Eyal Schneider Avatar answered Dec 05 '22 03:12

Eyal Schneider


That's because this.move<<4 returns an int.

When Java finds a shift operator it applies unary promotion to each operand; in this case, both operands are promoted to int, and so is the result. The behaviour is similar for other Java operators; see a related and instructive discussion, "Varying behavior for possible loss of precision".

like image 24
leonbloy Avatar answered Dec 05 '22 02:12

leonbloy