?
What is the output of the following program?
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);
}
}
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
Join the Discussion
Login to post a comment or share your explanation.
LoginIn 3rd case
Divide 325 with 256 then the remainder is 69
And that is the answer.
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