Concatenation of different types in Java

Viewed 65

I know, the question is very simple. But there are some small details that I need to fully understand (it is very important to understand what is happening in the background). Let's look at the piece code first. Why 2 consecutive "+" signs do not cause error here? Or is there an invisible 0 between those 2 "+'s"? In the first case, the reason the character is cast to the integer is 2 consecutive "+" signs, right?

public class AppleApp {
    public static void main(String[] args) {
        System.out.println("Apple is " + + '2' + " USD");
        // OUTPUT:   Apple is 50 USD
        System.out.println("Apple is " + + 2 + " USD");
        // OUTPUT:   Apple is 2 USD
    }
}
2 Answers

"Apple is " + + 2 + " USD" is 'parsed' as follows:

("Apple is " + (+2) + " USD" and +2 is just.. 2. Just like int x = +2; is legit, so is that.

The same applies to + + '2', because in java, characters are numbers (even where strings) aren't. '2' is the number 0x32 (the unicode code of the character 2).


char is a bit of a bizarre type; it's numeric. Specifically, a char represents a number between 0 and 65535, just like a byte is -128 to +127, and a short is from -32768 to +32767, and int is from -2147483648 to 2147483647.

Eventhough it is a number, all relevant methods that print things treat the number as a unicode value: They look up the number in the unicode table and show the character instead, i.e.:

char c = 65;
System.out.println(c);

prints A. That's not because of anything inherent in char, it's because of the println method.

In java, byte, short, and char are inferior: Many operations cannot be done on them, instead they're all converted to int first. That's because the spec says this.

Hence, +'A' is an expression that is of type int. A bit weird, but, spec says so. Hence, System.out.println(+'A') prints 65, because it calsl the int version of println which just prints 65, vs. System.out.println('A'); which calls the char version, which prints 'A'.

A char is a number, so read it as "Apple is " + (+'2') + " USD".

Same for the case with the integer.

Related