What is the /= operator in Java?
Asked Answered
O

7

10

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?

Onym answered 4/12, 2012 at 3:56 Comment(0)
S
17

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.

Seddon answered 4/12, 2012 at 3:58 Comment(0)
U
4

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.

Utta answered 4/12, 2012 at 4:2 Comment(0)
B
1

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: + - * / % & | ^

Brume answered 4/12, 2012 at 3:58 Comment(0)
U
1

a/=b; implies that divide a with b and put the result into a

Unhandsome answered 4/12, 2012 at 4:0 Comment(0)
G
1

X/=Y it is same as X=X/Y.
Also you can try the same thing for these operators + - * %

Goring answered 4/12, 2012 at 4:2 Comment(0)
J
0

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;
}
Jingoism answered 28/1, 2020 at 17:29 Comment(0)
D
-3

You could say a = a / b OR (for short) say a /= b

Defecate answered 7/4, 2021 at 17:54 Comment(1)
Your answer is not adding anything that was not already suggested by the numerous older answers.Lanza

© 2022 - 2024 — McMap. All rights reserved.