Why does the this arithmetic equal 10 and not 0 with a mod in Java
Question
I'm working on an old exam for a test and this code is printing the value of 10 for longVariable. Now, by hand, to me, the math would go 9 + 1 % 10 = remainder of 0, not 10... How am I wrong on this?
Thank you for helping!
public class ExamSectionA
{
public static void main(String[] args)
{
int intVariable1 = 9;
int intVariable2 = 10;
double doubleVariable = 11.2;
char charVariable = 'A';
long longVariable;
longVariable = intVariable1 + 1 % intVariable2;
intVariable2 = (int) (doubleVariable / 10f);
String[] theirSalary = {"10","20","30","40"};
System.out.println(intVariable2);
System.out.println(longVariable);
}
}
EDIT: PEMDAS. Think I got it.
Solution
Watch your order of operations:
intVariable1 + 1 % intVariable2;
is:
intVariable1 + (1 % intVariable2);
So 9 + 1 % 10
is being parsed as 9 + (1 % 10)
. Which gives 9 + 1 = 10
.
%
has higher precedence than +
.
OTHER TIPS
% operator has higher priority than +. For more information go here
Corrected code: (intVariable1 + 1) % intVariable2;
Did you mean instead (9+1) % 10
?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow