+ 1
How is math done in System.out.print()?
int m = 2; int n = 1; System.out.print(m + n + "" + m + n); //Output: 321 //My thought: 33
3 Réponses
+ 5
Given such output I guess it goes left to right, mind the "" that affects the output.
m + n => 3
3 + "" => "3"
Here the addition result is converted to string due to the presence of "".
"3" + 2 + 1
Here the + operator acts as string concatenation operator because the left-hand operand was a string. Rather than adding 2 and 1 again - the two numbers to the right are converted to string; and made "21".
"3" + "21" => "321" // final output
+ 3
The output is due the fact that the compiler evaluates the expression from left to right, because the operators have same precedence. When the string “” occurs, the rest of the expression is considered as a string (implicit typecast).
+ 3
Thanks for explanation!