6

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;
}
Daniel
  • 319
  • 2
  • 4
  • 12
  • 1
    In Java, binary operators (`op`) in expressions of the form `x = x op y` can be written as `x op= y`. Thus `minutes %= 60` is equivalent to `minutes = minutes % 60`. – user2864740 Nov 20 '13 at 00:47

3 Answers3

18

This is short for:

minutes = minutes % 60;

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

pobrelkey
  • 5,853
  • 20
  • 29
3

+= 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.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
1

It's a Modulo operation which is the same as taking the remainder from division. minutes%=60; is the same as minutes = minutes % 60; which is the same as minutes = minutes - (((int) (minutes/60)) * 60);

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249