2

I got little code here

int b=3;
b=b >> 1;
System.out.println(b);

It works perfectly, but when I change variable b to byte,short,float,double it contains errors, but with variables int and long it works perfectly, why it doesn't work with other variables?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Miljan Rakita
  • 1,433
  • 4
  • 23
  • 44

4 Answers4

7

The bit shift operators, e.g., >>, are compatible with any integral types. However, for smaller types like byte and short, the operation performs a widening conversion: the result is elevated to type int, and thus cannot be reassigned back to the source type.

Therefore, the following is not legal:

byte b = 3;
b = b >> 1;

But these assignments are legal:

byte b = 3;
b = (byte)(b >> 1)
int c = b >> 1;

As to why these operators don't work with float or double, I will leave that for you to explore. Hint: consider the layout of those types in memory and what the implications would be for bit shifting operators.

Mike Strobel
  • 25,075
  • 57
  • 69
1

The >> operator is defined for all integral types. It is not defined for float or double. With integral types, the result is always an int (or long, if the left operand is a long). Thus, when you use it with a byte or short, you need to cast back to the narrower integer type to do the assignment.

Section 15.19 of the Java Language Specification describes how the shift operators work. The first step is to apply unary numeric promotion to the operands; unary numeric promotion is described in Section 5.6.1 of the JLS.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

Following on Mike's answer, this problem exists on other operators too. We cannot even compile this program

    byte b = 3;
    b = b + 1;  // error

I think the language designer got a little lazy when they reached here and took a shortcut.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61
0

The simplest answer is that the operator must be defined for those types. The bitshift operators >> and << aren't defined for them.

This post explains it pretty well:

https://stackoverflow.com/a/1723938/2225842

If I understand correctly, this is the same for both Java and C++.

Community
  • 1
  • 1
Plasmarob
  • 1,321
  • 12
  • 20