Unexpected output

exercise No. 220

Q:

We consider:

Code Result
IO.print( "(" + 10 + " times more text" + ')' );
(10 times more text)
IO.print( '(' + 10 + " times more text" + ")" );
50 times more text)

Here "(" and '(' are being swapped and so are ')' and ")". Explain:

  1. Why do we get a value of 50?

  2. Why is there no opening parenthesis »(« in the second output?

A:

We first note that "(" is a a String literal while '(' is a char literal. Using the latter we have:

Code
IO.print('(');
IO.print((int)'(');
IO.print('(' + 0);
Result
(
40
40
Remark

Using overloaded ...print(char).

Casting char to int, thus using overloaded ...print(int): 40 is the »(« character's ASCII value.

Adding 0 implies an »char + int« addition resulting in ...print(int): Again 40 is the »(« character's ASCII value.

The question's first expression starts with a String literal "(". »Adding« 10 works by converting the int literal 10 into a String "10" prior to concatenating both into "(10". This continues until the char literal ')' is being implicitly converted into ")" and then being appended as well.

  1. The second expression starts wit a char literal '(' represented by the ASCII value of 40. Adding 10 this time is a regular char + int arithmetic operation yielding 50. Next follows the String literal " times more text". Thus 50 gets converted into "50" and the concatenation then yields "50 times more text".

  2. The first '(' brace is being consumed by the addition.

This task closely resembles Why using braces in IO.println(...) ? .