Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java syntax - extra plus sign after cast is valid?

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

like image 527
Ian2thedv Avatar asked Oct 09 '14 11:10

Ian2thedv


3 Answers

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;
like image 95
Peter Lawrey Avatar answered Nov 07 '22 01:11

Peter Lawrey


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)

like image 40
Dr. Debasish Jana Avatar answered Nov 07 '22 00:11

Dr. Debasish Jana


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.

like image 22
Mureinik Avatar answered Nov 07 '22 00:11

Mureinik