Skip to content

Assignment operators

Assignment operators assign a value to a variable. The basic assignment is =. Java also provides compound assignment operators that combine an operation with assignment.

OperatorDescriptionEquivalent
=Simple assignmenta = b
+=Add and assigna = a + b
-=Subtract and assigna = a - b
*=Multiply and assigna = a * b
/=Divide and assigna = a / b
%=Modulus and assigna = a % b
&=Bitwise AND and assigna = a & b
|=Bitwise OR and assigna = a | b
^=Bitwise XOR and assigna = a ^ b
<<=Left shift and assigna = a << b
>>=Right shift and assigna = a >> b
>>>=Unsigned right shift and assigna = a >>> b

Examples:

int x = 5;
x += 3; // x = 8
x *= 2; // x = 16
x %= 5; // x = 1
String s = "Hello";
s += " World"; // s = "Hello World"

Important: Compound assignments perform an implicit cast to the target type.

byte b = 10;
b += 5; // b = 15 (implicit cast, no error)
// b = b + 5; // error: int to byte requires cast