ExamVeda
Login
Home
Data Types and Variables
?

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

Answer & Solution
Correct Answer: Option C

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

Examveda
Question posted by Examveda
Community

Join the Discussion

4 Comments
Trending Kings
Trending Kings 5 years ago
Divide 325 with 256 then the remainder is 69
In 3rd case
Villa Aravind
Villa Aravind 9 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.
Gurdeep Sahotta
Gurdeep Sahotta 9 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
Judi Joshie
Judi Joshie 9 years ago
b = (byte) d ????