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);
}
}
A. 2
B. 129
C. -127
D. Compiler error
E. None of these
Answer: Option C
Solution(By Examveda Team)
Range of byte data in java is -128 to 127. But byte data type in java is cyclic in nature.
Join The Discussion
Comments ( 7 )
Related Questions on Data Types and Variables
What is the maximum value that can be stored in a byte variable in Java?
A. 127
B. 255
C. 32767
D. 64
What is the default value of an int variable in Java if it's not explicitly initialized?
A. 0
B. 1
C. -1
D. Null
Which of the following is not a valid identifier for a Java variable?
A. my_var
B. _myVar
C. 3rdVar
D. $var
Shouldn't we consider 0 as a value after 128?
c. -127 is correct answer. As b++ is b+=1 and += is implicit cast, means it cast the result from integer to byte automatically. Now 129(32 bit , as it was integer) is converted into 8 bit (byte can store 8 bit).
129 -> 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 :)
C is the correct answer
Byte range is from -127 to 128
b=127
b++= 128
after 128 it will back to -127 again..
b++= -127
Answer is -127 because Increment operators has implicit cast.
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.
result of arithmetic operation is int so it needs to type conversion, and here it stores in short so compilation error.....understand
can anyone help me,with detailed explanation..
the solution is not relevant.