+ 1

Could someone explain to me why this is the answer to this one question?

Question: What is the output of this code? int x = 8; System.out.print(++x * 3 + "" + x); Answer: 279 How is the answer to this 279..? Wouldnt it just be 32?

9th May 2019, 12:41 PM
RedishKitter
RedishKitter - avatar
3 Antworten
+ 1
Hello. The ++ is a precedent operator. Before 'x' is used, it gets an increment. So, ++x turns x in 9. Now, 9 * 3 equals 27. In the print, the string is concatenating the values 27 + "" + x. And x is 9 due to the incrementation. Since "" was used just to separate 27 + x (which would get a sum here) they're just separate values being put together one after another. Thus, 279. Hope it helps :)
9th May 2019, 12:51 PM
Breno Wilson
Breno Wilson - avatar
+ 1
Breno Wilson Ah thankyou! It all makes sense to me now :) Although I thought ++x wouldnt be counted in until after the line? I probably need to go revisit that chapter.
9th May 2019, 12:59 PM
RedishKitter
RedishKitter - avatar
+ 1
When a math is being doing, you need to solve it before printing. ++ (or --) has priority above multiplication and division. The catch is that the '+' from "" + x or 3 + "" isn't a sum, but a concatanation since you're "summing up" a string data with a number data (an integer in that case). You must pay attention to recognize that. You can follow my profile if you need any help I can solve :)
9th May 2019, 1:36 PM
Breno Wilson
Breno Wilson - avatar