The following code sample prints 1.5
.
float a = 3;
float b = 2;
a /= b;
System.out.println(a);
I don't understand what the /=
operator does. What is it supposed to represent?
The following code sample prints 1.5
.
float a = 3;
float b = 2;
a /= b;
System.out.println(a);
I don't understand what the /=
operator does. What is it supposed to represent?
It's a combination division-plus-assignment operator.
a /= b;
means divide a
by b
and put the result in a
.
There are similar operators for addition, subtraction, and multiplication: +=
, -=
and *=
.
%=
will do modulus.
>>=
and <<=
will do bit shifting.
It is an abbreviation for x = x / y (x /= y)
. What it does is it divides the variable to be asigned by the left hand side of it and stores it in the right hand side. You can always change:
x = x / y
to
x /= y
You can do this with most other operators like * / +
and -
. I am not sure about bitwise operators though.
A/=B means the same thing as A=(A/B)
Java (copying from C) has a whole set of operators X op = Y meaning X=X op Y, for op being any of: + - * / % & | ^
a/=b; implies that divide a with b and put the result into a
X/=Y
it is same as X=X/Y
.
Also you can try the same thing for these operators + - * %
As most people here have already said, x/=y
is used as a shortened form of x=x\y
and the same works for other operators like +=
, -=
, *=
, %=
. There's even further shortcuts for + and - where x++
and x--
represent x=x+1
and x=x-1
respectively.
One thing that hasn't been mentioned is that if this is used in some function call or conditional test the original value is used then replaced, letting you do the iterator for a while loop inside the call that uses that iterator, or write a true mod function using the remainder operator much more concisely:
public int mod(int a, int b){
return ((a%=b)>=0?a:a+b);
}
which is a much shorter way of writing:
public int mod(int a, int b){
a = a % b
if (a>=0){
return a;
}
return a+b;
}
You could say a = a / b
OR (for short) say a /= b
© 2022 - 2024 — McMap. All rights reserved.