Examveda
Examveda

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

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.


This Question Belongs to Java Program >> Data Types And Variables

Join The Discussion

Comments ( 7 )

  1. Arun Guru
    Arun Guru :
    3 years ago

    Shouldn't we consider 0 as a value after 128?

  2. Ved Prakash
    Ved Prakash :
    3 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 :)

  3. Acchu Superstar
    Acchu Superstar :
    6 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

  4. Gurdeep Sahotta
    Gurdeep Sahotta :
    7 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.

  5. GAURAV Singh
    GAURAV Singh :
    8 years ago

    result of arithmetic operation is int so it needs to type conversion, and here it stores in short so compilation error.....understand

  6. Mahendher Reddy
    Mahendher Reddy :
    8 years ago

    can anyone help me,with detailed explanation..

  7. Mukul Jindal
    Mukul Jindal :
    8 years ago

    the solution is not relevant.

Related Questions on Data Types and Variables