Java: space makes a difference in compilation?

I did a program (A Piglatin sort of ...) in which I inadvertently missed a variable in an expression:

String a = "R"++'a'; 

Actually it should be String a = "R"+text+'a'; . The compiler generated an error. But, when I did this:

 String a = "R"+ +'a'; 

Compiled program.

I wonder why space was placed, even though Java doesn’t care if you put a space or not in certain operators, for example: String a="ABCD"; matches String a = "ABCD";

Can someone explain this behavior?

+5
source share
4 answers

++ is a native operator (pre or post increment).

Putting between string and char literal is not syntactically valid.

But with "R"+ +'a' second + will be bound to the char literal a and will act as a unary plus (this operator has a very high priority). This is not a no-op: in Java, this affects the promotion of type a to int . This type of promotion means that the output will be R97 , not Ra (97 is the ASCII number for a ). The remaining + acts as a string concatenator.

+8
source

Since ++ is a unary operator, ++ is interpreted as follows:

  • "R"+ represents the string concatenation, and then the second argument (to calculate the concatenation)
  • +'a' represents the explicit setting of the ( + ) sign for the (numeric) char literal 'a' . Since you have explicitly set the sign of the value, it is treated as a number, and therefore the result +'a' is the number representation of the character 'a' , and therefore the result is R97 .

Similarly, if you did String a = "R"+ -'a'; , then the numerical value of 'a' (which is 97 ) will be canceled, and the result will be R-97 .

If, however, you simply ignored the + sign in front of 'a ', then 'a' considered as a character, not as a number, and the result would be Ra .

+2
source

String a = "R"++'a'; means "R"++ and 'a' . 'a' not added by the + operator, and therefore the error should be there. On the other hand, String a = "R"+ +'a'; means "R" , then a + , and then a +'a' (i.e. 97). Therefore, it compiles. The output will be R97

+2
source

The ++ operator applies to numbers and increments this value by 1. When you write + + 'c', it means you want to add a string and a positive char

0
source

Source: https://habr.com/ru/post/1237576/


All Articles