Examveda
Examveda

What is the output of the following program?
class A{
        public static void main(String args[]){
	        byte b;
   	        int i = 258;
	        double d = 325.59;

	        b = (byte) i;
	        System.out.print(b);

	        i = (int) d;
	        System.out.print(i);

                b = (byte) d;
                System.out.print(b);
        }
}

A. 258 325 325

B. 258 326 326

C. 2 325 69

D. Error

Answer: Option C

Solution(By Examveda Team)

In the type cast
b = (byte) i;
The value of i i.e 258 is cast into a byte variable. Whenever a casting done where source value is greater than the range of the destination then the result is the remainder of the division of source by the range of the destination. In this case the result is the remainder of the division of 258 by 256(the range of a byte), which is 2.

In the second type cast
i = (int) d;
the fractional component of d is lost and hence gives the output 325.

In the third type cast


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

Join The Discussion

Comments ( 4 )

  1. Trending Kings
    Trending Kings :
    3 years ago

    Divide 325 with 256 then the remainder is 69
    In 3rd case

  2. Villa Aravind
    Villa Aravind :
    6 years ago

    In the third case, same like the first case
    Divide 325 with 256 then the remainder is 69
    And that is the answer.

  3. Gurdeep Sahotta
    Gurdeep Sahotta :
    7 years ago

    In third case,
    b = (byte)d
    The value of b is 69 because, range of byte is:
    -128 to -1,0 to 127 (-128 to 127)
    means a byte can hold a total of 256 different values in the above range.
    initial value of d is 325.59, on casting to byte fraction part is ignored and
    only 325 is trying to store in b, but b can only take +ve values to 127.

    Here's how 325 is converted to 69 :

    (d) (b)
    0 0
    1 1
    2 2
    : :
    : :
    126 126
    127 127
    128 -128
    129 -127. .
    : :
    : :
    255 -1
    256 0
    257 1
    : :
    : :
    323 67
    324 68
    325 69

  4. Judi Joshie
    Judi Joshie :
    7 years ago

    b = (byte) d ????

Related Questions on Data Types and Variables