Java Assignment Operators
In Java, assignment operators are used to assign values to variables. They not only store values but can also modify the existing value of a variable based on a mathematical or bitwise operation.
The most basic assignment operator is the = operator, but Java also provides several compound assignment operators like +=, -=, *=, /=, etc., which make code shorter and easier to read.
List of Assignment Operators in Java
Operator | Description | Example |
= | Simple assignment. Assigns RHS value to LHS variable. | C = A + B; → C gets A + B |
+= | Add and assign. C += A; → same as C = C + A | C += A; |
-= | Subtract and assign. C -= A; → same as C = C - A | C -= A; |
*= | Multiply and assign. C *= A; → same as C = C * A | C *= A; |
/= | Divide and assign. C /= A; → same as C = C / A | C /= A; |
%= | Modulus and assign. C %= A; → same as C = C % A | C %= A; |
<<= | Left shift and assign. C <<= 2; → same as C = C << 2 | C <<= 2; |
| Right shift and assign. C >>= 2; → same as C = C >> 2 | C >>= 2; |
&= | Bitwise AND and assign. C &= 2; → same as C = C & 2 | C &= 2; |
^= | Bitwise XOR and assign. C ^= 2; → same as C = C ^ 2 | C ^= 2; |
|= | Bitwise OR and assign. C |= 2; → same as C = C | 2 | C |= 2; |
Example 1: Basic Assignment Operations
In this example, we’ll create three integer variables a, b, and c and perform basic assignment operations like simple assignment, addition assignment, subtraction assignment, and multiplication assignment.
public class Test {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c);
c += a;
System.out.println("c += a = " + c);
c -= a;
System.out.println("c -= a = " + c);
c *= a;
System.out.println("c *= a = " + c);
}
}c = a + b = 30 c += a = 40 c -= a = 30 c *= a = 300
Example 2: Division, Modulus, and Bitwise Assignments
public class Test {
public static void main(String[] args) {
int a = 10;
int c = 15;
c /= a;
System.out.println("c /= a = " + c);
c = 15;
c %= a;
System.out.println("c %= a = " + c);
c = 15;
c &= a;
System.out.println("c &= a = " + c);
c = 15;
c ^= a;
System.out.println("c ^= a = " + c);
c = 15;
c |= a;
System.out.println("c |= a = " + c);
}
}c /= a = 1 c %= a = 5 c &= a = 10 c ^= a = 5 c |= a = 15
Example 3: Shift Assignment Operators
public class Test {
public static void main(String[] args) {
int a = 10;
int c = 0;
c <<= 2;
System.out.println("c <<= 2 = " + c);
c = 15;
c >>= 2;
System.out.println("c >>= 2 = " + c);
}
}c <<= 2 = 0 c >>= 2 = 3
Summary
Operator | Operation | Equivalent To |
+= | Add and assign | x = x + y |
-= | Subtract and assign | x = x - y |
*= | Multiply and assign | x = x * y |
/= | Divide and assign | x = x / y |
%= | Modulus and assign | x = x % y |
<<= | Left shift and assign | x = x << y |
| Right shift and assign | x = x >> y |
&= | Bitwise AND and assign | x = x & y |
^= | Bitwise XOR and assign | x = x ^ y |
|= | Bitwise OR and assign | x = x | y |