+ 3

Got a sec to explain correct output?

I get tripped up on order precedence and these simple questions kill me in challenges. Can someone please break this down for me? What is the output of this code? int x = 19; int y = 7; System.out.println(x / y % 3);

13th Oct 2019, 3:53 PM
will
will - avatar
3 odpowiedzi
+ 3
Yup. What's basically happening is... System.out.print(19 / 7 % 3); Java interpreter reads this from left to right as the division operator(/) and the modulus operator(%) have the same precedence. So it gets pretty simple from here on. 19 / 7 = 2 And then, 2 % 3 = 2 You got this? The / operator works by giving the quotient as the output. While the % operator gives us the remainder. If you want to learn about operator precedence in Java, it goes like this.. 1) Brackets or Parenthesis 2) Division/Multiplication/Modulus(All happen simultaneously, left to right) 3) Addition/Subtraction.
13th Oct 2019, 4:03 PM
Aaron Stone
Aaron Stone - avatar
+ 3
Thanks Aaron Stone , it's the modulus that tripped me up, and now I know why. Most modulus examples and excercises give you a nice big number on the left and a smaller number on the right... (6 % 5) Which makes for quick division to realize you have a remainder of... (1) I somehow got it into my head that since (2 / 3) is ( .666666) or whatever, there was something wrong, but the fix was simpler than that, in the case of the modulus operation in question, (3) goes into (2) zero times, which means you're stuck with a remainder of (2) from the gate, no division necessary 🤦‍♂️ Doubt I'm the only person who runs into this, at least while they're learning, or until they learn Another post that helped me see the light https://stackoverflow.com/q/17524673/11897018
13th Oct 2019, 4:44 PM
will
will - avatar
0
@wil nice!
13th Oct 2019, 5:03 PM
Aaron Stone
Aaron Stone - avatar