Ian2thedv
Ian2thedv

Reputation: 2701

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

Upvotes: 16

Views: 1124

Answers (3)

Mureinik
Mureinik

Reputation: 312086

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.

Upvotes: 5

Peter Lawrey
Peter Lawrey

Reputation: 533780

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;

Upvotes: 26

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7128

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)

Upvotes: 7

Related Questions