0

I have this piece of code in java. I get the output as -1 (I was expecting an error though..). explain please! why?

public class Main {
    public static void main(String[] args) {
    int a=0xfffff;
    byte b = (byte)a;
    System.out.println(b);
    }
}
Patriotic
  • 2,103
  • 4
  • 26
  • 36
  • You are converting hex value into int(0xfffff=1048575).Then int value into bytes(1048575=-1).You are getting -1 because range of bytes is -128 to 127.so if you convert int value 127,128,254,255,256,257..... to byte ,you will get consecutively 127,-128,-2,-1,0,1.....Please see the links that has previous answers. – Patriotic Jul 02 '17 at 14:19
  • Why would you expect an error? http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.3 should have set your expectation that there would not be an error. Why didn't it? – Lew Bloch Jul 02 '17 at 14:58

0 Answers0