Few days ago, I made a typo in java code but it compiled and worked well. (though the result is strange.)
My code is:
public static void main(String args[]) {
String strOut;
char cSEP = '|';
String sSEP = "|";
strOut = "AA" + cSEP + "BB"; // Correct assignment
System.out.println(strOut); // The result is "AA|BB". This is OK.
strOut = "AA" + + cSEP + "BB"; // No Error : no token between two +
System.out.println(strOut); // The result is "AA124BB"
strOut = "AA" + + sSEP + "BB"; // This is compiler error !!!
System.out.println(strOut);
}
I cannot find why the 2nd assignment is not error and 124 is printed. (Of course, '|' is 124 in ASCII code. But why "124", not "|" ?)
Is this compiler bug? Or correct java syntax that I did not know yet ?
The difference between a String
and a char
is significant. some numeric operators, when applied on a char
, turns the char
into an int
(this is called unary numeric promotion). On the other hand, only the binary +
operator is defined for String
s.
In the second and third line of your code, the expression is parsed like this:
strOut = "AA" + (+ cSEP) + "BB";
The unary +
operator, when applied on a char
, turns the whole expression into an int
through unary numeric promotion. The value is equal to the encoded value of the character. So the expression becomes:
strOut = "AA" + 124 + "BB";
which is valid.
But if cSEP
were to be replaced with sSEP
:
strOut = "AA" + (+ sSEP) + "BB";
The Java compiler doesn't know what + sSEP
means. The +
unary operator is not defined for String
!