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);
}
}
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
Join The Discussion
Comments ( 4 )
What is the maximum value that can be stored in a byte variable in Java?
A. 127
B. 255
C. 32767
D. 64
What is the default value of an int variable in Java if it's not explicitly initialized?
A. 0
B. 1
C. -1
D. Null
Which of the following is not a valid identifier for a Java variable?
A. my_var
B. _myVar
C. 3rdVar
D. $var
Divide 325 with 256 then the remainder is 69
In 3rd case
In the third case, same like the first case
Divide 325 with 256 then the remainder is 69
And that is the answer.
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
b = (byte) d ????