“Possible loss of accuracy” is a crash in Java, or am I missing something?

I get the error "loss of accuracy" when it should not be, 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, moving is still a byte, and the rest is 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 tried many options, but still getting the same error.

Now I don’t know.

+4
java casting precision
source share
3 answers

In fact, all logical operators (& | ^) return int , regardless of their operands. You must also indicate the final result x | y.

+8
source share

This is because this.move<<4 returns int.

When Java finds a shift operator , it applies unary advance to each operand; in this case, both operands advance to int , and therefore the result. The behavior is similar for other Java statements; see relevant and instructive discussion, Changing behavior for possible loss of accuracy .

+8
source share

Bitwise operands of OR are subject to binary digital advancement. Here's how it is "defined in JLS,

5.6.2 Binary numeric promotion

When an operator applies binary code numerical advancement to a pair of operands, each of which must denote a value of a numeric type, the following rules apply to using the extension transform (§5.1.2) to convert the operands if necessary:

  • If either the operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

As you can see, there is no byte type, so by default all bytes are incremented to int. You need to return it back to byte to get rid of the warning,

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

All Articles