Search code examples
javacasting

How to get value of byte that belongs to out of range?


{double a = 295.04;
int b = 300;
 byte c = (byte) a;
 byte d = (byte) b;
 System.out.Println(c +" " + d);}

Storage size of byte is 8 bits and maximum positive byte value is 127.so c isn't equal to 300.Then I tried to convert 300 to binary number.The binary number(of 300) has 9 bits.I confused to get value of c and d . why do I get c = 39 and d = 44 ?


Solution

  • Byte is signed primitive datatype in java. When we assign something bigger than byte value, It is like a cycle.

    Suppose you entered 300 in byte variable. After first cycle byte variable filed with 0,127 means 128 place // 300-128 = 172

    After second cycle byte variable filed with 0,127 means 128 place // 172-128 = 44

    Now in the third cycle it is 44. I hope this will answer your query.