?
What will be output of following program?
What will be output of following program?
public class Test{
public static void main(String[] args){
byte b=127;
b++;
b++;
System.out.println(b);
}
}
public class Test{
public static void main(String[] args){
byte b=127;
b++;
b++;
System.out.println(b);
}
}
Answer & Solution
Correct Answer:
Option
C
Range of byte data in java is -128 to 127. But byte data type in java is cyclic in nature.
Join the Discussion
Login to post a comment or share your explanation.
Login129 -> 10000001 , As we know that byte are signed and left most digit represent the sign (0 means positive and 1 means negative), here the left most value is 1 (in 10000001) so negative of it will be the answer , to find the negative we do 2's complement and add 1 to it
10000001 -----> 01111110 (2's complement) +1 ---> 01111111 = 127
and as we already know the left most bit was 1 so it is -127
hope this helps :)
Byte range is from -127 to 128
b=127
b++= 128
after 128 it will back to -127 again..
b++= -127
b++;
is equivalent to
b = (byte) (b + 1);
but, on the other hand,
b = b + 1;
is a simple arithmetic operation and need type caste from int to byte.