+ 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

26th Aug 2019, 4:57 AM
你知道規則,我也是
你知道規則,我也是 - avatar
3 Antworten
+ 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
26th Aug 2019, 5:15 AM
Ipang
+ 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).
26th Aug 2019, 5:12 AM
Michael
Michael - avatar
+ 3
Thanks for explanation!
26th Aug 2019, 5:17 AM
你知道規則,我也是
你知道規則,我也是 - avatar