Weird output.

exercise No. 212

Q:

We consider:

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

So "(" is being replaced by '(' and ')' by ")". Something is weird here:

  • Why do we get a value of 50?

  • Why is there no opening brace »(« in the second output?

  • Why is the closing brace »)« present in the first output despite a similar change happening at expression end as well?

Give an explanation.

A:

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

Code
System.out.print('(');
System.out.print((int)'(');
Result
(
40
Remark

Using overloaded ...print(char).

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

Te 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.

The second expression starts wit a char literal '(' representing 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".

This snippet's idea closely resembles Why using braces in IO.println(...) ? .