+ 3
How to calculate byte operations in java?
byte x=(byte)(417.35) byte y=(byte)(128) byte z=(byte)(-127)
6 Respostas
+ 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.
+ 2
What is the answer? And how did it came?
+ 2
x=-95
y=-127
z=128
But how???
+ 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.
+ 1
It's little bit complicated.
- 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