Problem while printing characters Difference between System.out.println('A') and System.out.println(+'A') [closed]
https://softwareengineering.stackexchange.com/questions/328879
Pergunta
Why is it that :
System.out.println(+'A') //gives output as 65
System.out.println('A') //gives output as A
Also
System.out.println(8+4+'A'+"PRIME"+4+4+'A');
gives output as 77PRIME44A
Why is it that 8+4 before the String "Prime" are being added, while 4+4 after "Prime" are being printed as it is ?
I also have a doubt why 8+4+'A' results in 65(ascii of A)+12=77 whereas 4+4+'A' doesn't include A's ascii getting added up ?
Is there any specific rule or convention regarding the above ?
Solução
System.out.println(+'A') //gives output as 65
In the expression +'A'
the unary plus operator (indicating a positive integer) gets applied to 'A'
and the expression only makes sense if the char is converted to an int
. The character 'A'
has the int value of 65 (see the ASCII table), which is why the whole expression evaluates to 65, which then gets printed.
System.out.println(8+4+'A'+"PRIME"+4+4+'A');
gives output as 77PRIME44A
Why is it that 8+4 before the String "Prime" are being added, while 4+4 after "Prime" are being printed as it is ?
Because the associativity of +
(both for integer addition and for string concatenation) is left-to-right. So first you do 8+4
, which is integer addition, then 12+'A'
(which requires 'A'
to be interpreted as its integer value 65), and then you have +"PRIME"
. But this only makes sense as string concatenation, which is why it results in "77PRIME"
; afterwards every call to +
is a string concatenation; the integers get converted to their string equivalents (4 -> "4") and the result of a string + char operation shouldn't surprise you.
So it's
8+4+'A'+"PRIME"+4+4+'A'
--> ((((((8+4)+'A')+"PRIME")+4)+4)+'A') // placed explicit parenthesis
--> (((((12+'A')+"PRIME")+4)+4)+'A') // int addition 8+4
--> ((((77+"PRIME")+4)+4)+'A') // int addition, 'A' cast to int 65
--> ((("77PRIME")+4)+4)+'A') // string concat, 77 converted to "77"
--> (("77PRIME4"+4)+'A') // string concat, 4 --> "4"
--> ("77PRIME44"+'A') // ditto
--> "77PRIME44A" // string + char concat