+ 3

How to calculate byte operations in java?

byte x=(byte)(417.35) byte y=(byte)(128) byte z=(byte)(-127)

4th Jun 2020, 3:39 PM
Arya
Arya - avatar
6 Respuestas
+ 1
127 is the upper limit so adding 1 to it will overflow to -128 which is the lower limit. So 128 will print -127. -127 is in the range so it is printed as it is. 417 calculated as 127 + 129 = 0, and 0 + 127 = 127 which adds up to 383. Now 383 + 34 = 417. So 127 + 1 = -128 and -128 + 33 = -95. This might not be clear now but once you understand it, it will be easy. Read on overflow and underflow in Java.
5th Jun 2020, 10:57 AM
Avinesh
Avinesh - avatar
+ 2
What is the answer? And how did it came?
5th Jun 2020, 10:39 AM
Arya
Arya - avatar
+ 2
x=-95 y=-127 z=128 But how???
5th Jun 2020, 10:40 AM
Arya
Arya - avatar
+ 1
This is a simple case of overflow in Java where the value to be contained is greater than the range of the type it is stored in. Since byte can store only values from -128 to 127, when you say 128, it is stored as -128 since 127+1 overflows to the lower range of byte. In the same way you can do the calculation for 417 to understand it better.
4th Jun 2020, 6:35 PM
Avinesh
Avinesh - avatar
+ 1
It's little bit complicated.
5th Jun 2020, 2:16 PM
Naveed
Naveed - avatar
- 1
remember that the byte values ​​are from -128 to 127, so the values ​​you have entered cause data loss, better use a suitable data type such as int or float
4th Jun 2020, 5:51 PM
Astral