So I came across something that confused me when casting a byte
to char
, usually I would do this:
for (byte b:"ABCDE".getBytes()) {
System.out.println((char)b);
}
Which will print out
A
B
C
D
E
I accidentally left a +
between the (char)
and b
and got the same result!?
Like so:
for (byte b:"ABCDE".getBytes()) {
System.out.println((char) + b);
}
Why exactly is this happening?
Am I essentially doing (char)(0x00 + b)
? Because
System.out.println((char) - b);
yields a different result.
Note: Using Java version 1.8.0_20
Why exactly is this happening?
If you put a unary -
operator before a number or expression it negates it.
Similarly, if you put a unary +
operator before a number or expression it does nothing.
A safer way to convert a byte to a char is
char ch = (char)(b & 0xFF);
This will work for characters between 0 and 255, rather than 0 to 127.
BTW you can use unary operators to write some confusing code like
int i = (int) + (long) - (char) + (byte) 1; // i = -1;
b is a byte, and that be expressed as + b as well. For example, 3 can be written as +3 as well. So, ((char) + b) is same as ((char) b)
The +
is the unary plus operator - like you can say that 1
is equivalent to +1
, b
is equivalent to +b
. The space between +
and b
is inconsequential. This operator has a higher precedence than the cast, so after it's applied (doing nothing, as noted), the resulting byte
is then cast to a char
and produces the same result as before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With