The problem occurs because the cast that lets the code compiles
implicitly auto-masks the bits.
For example, with the values you mentioned.
byte b = 129;
will generate a compiler error (Type Mismatch).
but, adding the cast lets it compile:
byte b = (byte)129;
To see this a little better, create a class with the following method
to show bits in a byte:
public void testConvert(int val){
byte b = (byte)val;
for(int i = 7;i>=0;i--){
System.out.print( (b>>i)&1);
}
System.out.println("");
System.out.println(b);
}
then disassemble it with: javap -s -c -classpath $CLASSPATH
yourClassName
You will see the following:
public void testConvert(int);
Signature: (I)V
Code:
0: iload_1
1: i2b
2: istore_2
3: bipush 7
5: istore_3
....
take note of the mnemonic "i2b", (integer to byte) (opcode 0x91) this
converts the integer with the rule intVal & 0xFF. This actually ignores
the sing of the incoming value. The reason you see the negative number
is because "byte" is a signed type, so when the high bit is on, you get
a negative number.
So, I afraid that if you want an exception to occur in this case, you
may want to replace casts with a method call, and let the method throw
the exception.
Along the lines of:
private byte int2Byte(int val){
byte b = (byte)val;
if( (b&0xFF) != val){
throw new RuntimeException("integer too big");
}
return b;
}
Change the 0xFF to 0x7F to overflow your 129 value (129 does not really
overflow a byte)
hth