Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : space makes a difference in compilation?

Tags:

java

string

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?

like image 991
dryairship Avatar asked Dec 07 '15 13:12

dryairship


2 Answers

++ 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.

like image 176
Bathsheba Avatar answered Nov 15 '22 03:11

Bathsheba


Because ++ is a unary operator, while + + is interpret as following:

  1. "R"+ represents a string concatenation and then the second argument (for the concatenation is evaluated)
  2. +'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.

like image 43
Konstantin Yovkov Avatar answered Nov 15 '22 02:11

Konstantin Yovkov