+ 5

Can anyone tell why I'm getting the following output in System.out.println(1+2+” = “+1+2); and output is 3=12??

12th Mar 2017, 9:39 AM
Sagar Maharana
Sagar Maharana - avatar
2 Answers
+ 3
The value inside the () is getting evaluated from left to right. First it looks at 1+2 and evaluates to 3. Then it sees you want to add the string " = " to it, and therefore turns the three into a sting. Now when you want to add 1 to the string it adds it onto the string, so "3 = " + 1 turns into "3 = 1", and then the two gets added to the end as well. You can use parenthesis to make it evaluate the numbers first and then print the string like this: System.out.println((1+2) + " = " +(1+2)); Now the 1+2 gets added first on both ends before the answers get turned into a string. Hope this helps clear up the confusion :)
12th Mar 2017, 10:10 AM
Frans Booysen
Frans Booysen - avatar
+ 3
thnks frans
15th Mar 2017, 1:42 AM
Sagar Maharana
Sagar Maharana - avatar