Search code examples
javaconcatenationstring-formattingstring-concatenationtype-promotion

String operations using different operators


I used this statement

System.out.println("Y"+90+90);

The answer Java shows is Y9090. I understand how Java does this operation. A string is concatenated with the literals if the operator + is used. Therefore Y is concatenated with 90 first, forming Y90 as a new string and then again Y90 is concatenated with 90 forming Y9090 as the resultant string.

When I change the above expression to:

System.out.println("Y"+90-90); 

Java shows an error. In this one, Y is concatenated with 90, forming Y90 as a new string. This new string faces with the - operator and produces an error.

But if i write this:

System.out.println("Y"+90*90);

It shows the answer as Y8100.

How can it be possible? It should have produced an error or Java should have produced a similar answer for the second statement like Y0 without producing error.


Solution

  • With both pluses, the operators are evaluated left to right, so "Y" + 90 + 90 is equal to ("Y" + 90) + 90.

    With a plus and minus, which have the same precedence, the same is true. "Y" + 90 - 90 is equal to ("Y" + 90) - 90. You can't subtract a number from a string, hence the compilation error.

    With a plus and a multiplier, multiply has higher precedence so "Y" + 90 * 90 is "Y" + (90 * 90) which compiles fine.

    When in doubt, add parentheses to show your intent.