why explicit type casting required from double to float but not from int to byte?

前端 未结 4 1378
失恋的感觉
失恋的感觉 2020-12-20 20:32

Consider following statement:

byte by = 5; //works fine

literal \'5\' is of type int and small enough to fit into a variable of type byt

4条回答
  •  天涯浪人
    2020-12-20 21:14

    Agreed with Jon, However, I would like to add that

    byte by = 5;     //works fine until the number is less than 128 
    

    This is because one byte can only hold upto -128 to 127. Once you will try to enter number above 127, you will get the same error like you get when storing double value into float.

    byte by =  128; //compilation error
    

    So for agreeing the lost of the conversion data, you need to perform the explicit conversion.

    byte by = (byte) 128; // work fine
    

提交回复
热议问题