3,388 views
0 votes
0 votes

What is the output of this program?
 

class Conversion {
    public static void main(String args[]) 
    { 
        double a = 295.04;
        int b = 300;
        byte c = (byte) a;
        byte d = (byte) b;
        System.out.println(c + " " + d);
    } 
}


a) 38 43
b) 39 44
c) 295 300
d) 295.04 300

1 Answer

Best answer
3 votes
3 votes
b) 39 44
 

PS: This is Java code and the rules of Java do not apply to C/C++.

Byte data type being of 8 bits can hold only 256 unique values.

Hence during type casting value changes. For integer the lowest 8 bits is assigned to byte, and for double/float the lowest 8 bits of its integer part is assigned to byte. One more thing is in Java, this type conversion is not IMPLICIT and without being explicity type casted if we assign a higher type to a byte, COMPILE ERROR results (but we can assign a lower sized variable to a higher sized one like int a = b; where b is a byte). Here, we get the following result:

c = a mod 256 = 39 (taking the lowest 8 bits)

d = b mod 256= 44 (taking the lowest 8 bits from the corresponding integer representation)

PS: In Java there is no concept of unsigned and hence for a byte, if the MSB is 1, it becomes negative (2's complement representation). This is similar to "signed char" in C.
edited by
Answer:

Related questions

1 votes
1 votes
1 answer
1
LavTheRawkstar asked Jun 28, 2016
2,144 views
Which of the following methods from Object is final ( that it cannot be overriden ) ?(A) finalize method(B) clone method(C) hashCode method(D) getClass method
0 votes
0 votes
1 answer
4
sh!va asked Sep 2, 2016
373 views
Spot the features that are present in C++ not in Java:I. New operator II. Delete opeartor III. Objects stored in stack memory. IV . Objects stored in Heap memorya. ...