Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does %= mean in Java?

How does %= work in Java? I've been told that it can be used to reassign a value?

Grateful if anyone could teach! Thanks!

minutes=0;
while(true){
minutes++;
minutes%=60;
}
like image 842
Daniel Avatar asked Nov 20 '13 00:11

Daniel


2 Answers

This is short for:

minutes = minutes % 60;

There are other, similar compound assignment operators for all the binary operators in Java: +=, -=, *=, ^=, ||=, etc.

like image 165
pobrelkey Avatar answered Sep 23 '22 07:09

pobrelkey


+= is add to:

i+=2;

is i = i + 2;

% is remainder: 126 % 10 is 6.

Extending this logic, %= is set to remainder:

minutes%=60;

sets minutes to minutes % 60, which is the remainder when minutes is divided by 60. This is to keep minutes from overflowing past 59.

like image 40
nanofarad Avatar answered Sep 23 '22 07:09

nanofarad