Modulus Assign Operator

If we want to divide a variable with some value, and then assign the modulus or remainder back to the original variable, then the Modulus Assign Operator is a better way of doing it. This operator when written is more concise and intuitive. Below are some examples on how to do Modulus Assign Operator in Java.

Modulus Assign With Literal

Since modulus assign operator combines the modulus operation with the assign operation, the symbol to do this is %=. Because % is the symbol for modulus and = is the symbol for assignment. Below is a simple example:
int a = 27;
a %= 5;
System.out.println(a);
For those unfamiliar, modulus means to divide and get the remainder of the division operation. Hence the above code divides 27 by 5 and gets the remainder which is 2. And that remainder is assigned back to variable a. Hence we get below result:
2

Modulus Assign With Another variable

We can use another variable to divide the original variable to get the remainder. In case we can't hard code the literal:

int a = 23;
int b = 10;
a %= b;
System.out.println(a);

So we divide a with b, which is 23 divided by 10, and get the remainder which is 3. The answer is assigned to the variable a. Hence the below result of the code when run:
3

Modulus Assign With An Expression

We are not limited to divide the variable with a literal or another variable, we can do via expression. See below example:
int a = 15;
int b = 3;
a %= b * 2;
System.out.println(a);
So we evaluate the right expression first, which is 3 multiplied by 2, that is 6. Then we divide a with 6, which is 15 divided by 6, and the remainder is 3. Hence a is assigned the value given below:
3