1

For example, we have

char char1 = 0, char2 = 0;

This works fine:

char1 |= char2;

This does not:

char1 = char1 | char2;

The latter leads to "error: incompatible types: possible lossy conversion from int to char"

Why these options have different behavior?
Where "int" has emerged? According to Oracle:

  • bitwise operators "can be applied to any of the integral types"
  • char is an integral type
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • Interesting question. Why do you want this, what are you trying to obtain? The short answer is that the funny and unexpected behaviour is taken over from C and C++ – Ole V.V. Mar 02 '23 at 08:15
  • 1
    I am afraid you over-interpreted [the tutorial](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html). It says that bitwise operators can be applied to integral types and that `~` (complement) *can be applied to any of the integral types*. Easy to misunderstand. What it does not say is that using `|` (or) on `char` first promotes the operands to `int`. Yeah, it’s confusing. – Ole V.V. Mar 02 '23 at 08:28
  • 1
    Thank you all! I have found [the complete answer](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2). From now on I will carefully read the tutorial: "perform bitwise and bit shift operations on integral types" does not mean that it preserves that types. – Tempally Smith Mar 06 '23 at 11:32

0 Answers0