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;
}
This is short for:
minutes = minutes % 60;
There are other, similar compound assignment operators for all the binary operators in Java: +=
, -=
, *=
, ^=
, ||=
, etc.
+= 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With