1,963 views

### 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

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.

sir bygod i always give respect.

whenever i talk with u or anyone else also then also i call him or her as mam or sir.

you are blaming me for no reason and putting taunts to me
I was not blaming you - there are many people who thinks calling "mam" or "sir" is respect. We in India always do that to teachers. But actual respect is in doing what the teacher says and not doing the opposite and just calling "sir" or "madam". In top institutes like IISc, some students call professors by first name and this is the standard in developed countries also.

Anyway by respect I meant that you should not disturb others - especially those who answer you. Every one here want answer to their queries- but answering takes a lot of time as this is not history or literature where answers can be just written without thinking. I just edited the answer to this question - it took me more than 15 minutes to do so because I had to write, compile, test and then to write. Did you try compiling before posting the question? If not you are never going to understand the solution however someone explains it. Someone can feed you some tricks which works for many cases, but will fail when someone sets question properly as in GATE.

I can answer this question better- but currently you won't get it - because you are looking for tricks. To answer this your mind should work like a compiler which requires proper knowledge of language semantics. Then after each line you can know the possible values and answer any question of this type.

Thanks Arjun for the edit .Now the answer is more sound and strong.

1 vote
1
1,929 views