ExamVeda
Login
Home
Data Types and Variables
?

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);
      }
}

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.

Examveda
Question posted by Examveda
Community

Join the Discussion

7 Comments
Arun Guru
Arun Guru 5 years ago
Shouldn't we consider 0 as a value after 128?
Ved Prakash
Ved Prakash 6 years ago
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 :)
Acchu Superstar
Acchu Superstar 8 years ago
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
Gurdeep Sahotta
Gurdeep Sahotta 9 years ago
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.
GAURAV Singh
GAURAV Singh 10 years ago
result of arithmetic operation is int so it needs to type conversion, and here it stores in short so compilation error.....understand
Mahendher Reddy
Mahendher Reddy 10 years ago
can anyone help me,with detailed explanation..
Mukul Jindal
Mukul Jindal 10 years ago
the solution is not relevant.