3,594 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

2.2k
views
1 answers
1 votes
LavTheRawkstar asked Jun 28, 2016
2,178 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
360
views
0 answers
0 votes
rayhanrjt asked Dec 15, 2022
360 views
Suppose, you are implementing Overdraft Account (OD) class using java for a banking app. An OD type account is opened with an approved loan limit ( ... problems mentioned in the question? Write necessary java codes to solve the problem.
327
views
0 answers
0 votes
AlexanderGallaghers asked Jun 14, 2018
327 views
I want some information about the programming language java.What is java?what are the features of java?And what are the structure of java program and compare ... service is helping to get the genuine essay? Is this service is beneficial?
397
views
1 answers
0 votes
sh!va asked Sep 2, 2016
397 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 ... onlyb. II and III onlyc. III onlyd. All features are present in C++ and Java