I was making a program (A Piglatin sort of...), in which I unintentionally missed a variable in the statement:
String a = "R"++'a';
It should actually have been String a = "R"+text+'a';
. The compiler produced an error. But, when I made it:
String a = "R"+ +'a';
The program compiled.
I am wondering why putting a space made the difference even though Java does not care whether you put a space or not in certain statements, like : String a="ABCD";
is the same as String a = "ABCD";
Can someone please explain this behavior?
++
is an operator in its own right (pre or post increment).
Putting it between a string and a char literal is not syntactically valid.
But with "R"+ +'a'
, the second +
will bind to the char literal a
and will act as the unary plus operator (this operator has a very high precedence). This is not a no-op: in Java it has the effect of promoting the type of a
to an int
. This type promotion means that the output will be R97
rather than Ra
(97 is the ASCII number for a
). The remaining +
acts as the string concatenator.
Because ++
is a unary operator, while + +
is interpret as following:
"R"+
represents a string concatenation and then the second argument (for the concatenation is evaluated)+'a'
represents an explicit setting of sign (+
) to the (numeric) char
literal 'a'
. Because you've explicitly set the sign of the value, it is treated as a numeric one and hence the result of +'a'
is the numeric representation of the character 'a'
and that's why the result is R97
.The same way if you did String a = "R"+ -'a';
then the numeric value of 'a'
(which is 97
) would be negated and the result would be R-97
.
If you, however, had just ignored the +
sign before 'a
', then 'a'
would have been treated as character, not as numeric, and the result would be Ra
.
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