0

can someone tell me why the following code is throwing the compile error "cannot convert from int to byte"?

byte x = 2;  
byte y = (x >> 1);

I mean I clearly declared both x and y as bytes, and 'x >> 1' will evaluate to 1 i.e. still be in the range of a byte.
Also when I do something like

byte x = -2;  
System.out.println(x >>> 1);

I would expect 126 to be the outcome, because I shifted a 0 in the leftmost bit of b1111 1101, which is 0111 1110. But the console is printing '2147483647', so it looks like my byte has been converted to an integer before the 0 has been shifted in. Why is that? Please help me out.

2

1 Answer 1

4

Simply because x >> 1 returns an int so you simply need to cast it explicitly to a byte as next:

byte y = (byte)(x >> 1);

Please also note that since it is an int operator (or long depending on the left-hand operant cf §15.19 from the specification), all its operands must be of type int which means that in your case x will be implicitly converted into an int too in other words x >> 1 is equivalent to (int)x >> 1

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.