Assignment Operators
Assignment operators in Java are used to assign values to variables. The most common assignment operator is =. Java also provides shorthand operators for arithmetic and bitwise operations.
| Operator | Description | Example | Equivalent To |
|---|---|---|---|
| = | Assigns value to a variable | a = 10; | a = 10; |
| += | Adds and assigns | a += 5; | a = a + 5; |
| -= | Subtracts and assigns | a -= 3; | a = a - 3; |
| *= | Multiplies and assigns | a *= 2; | a = a * 2; |
| /= | Divides and assigns | a /= 4; | a = a / 4; |
| %= | Modulus and assigns | a %= 3; | a = a % 3; |
| &= | Bitwise AND and assigns | a &= 2; | a = a & 2; |
| |= | Bitwise OR and assigns | a |= 2; | a = a | 2; |
| ^= | Bitwise XOR and assigns | a ^= 1; | a = a ^ 1; |
| <<= | Left shift and assigns | a <<= 2; | a = a << 2; |
| >>= | Right shift and assigns | a >>= 1; | a = a >> 1; |
Source Code:
public class AssignmentOperators{
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("Initial values: a = " + a + ", b = " + b);
// Simple assignment
a = b;
System.out.println("After a = b, a = " + a); //5
// Add and assign
a += 3; // Equivalent to: a = 5 + 3;
System.out.println("After a += 3, a = " + a); //8
// Subtract and assign
a -= 2; // Equivalent to: a = 8 - 2;
System.out.println("After a -= 2, a = " + a); //6
// Multiply and assign
a *= 4; // Equivalent to: a = 6 * 4;
System.out.println("After a *= 4, a = " + a); //24
// Divide and assign
a /= 2; // Equivalent to: a = 24 / 2;
System.out.println("After a /= 2, a = " + a); //12
// Modulus and assign
a %= 3; // Equivalent to: a = 12 % 3;
System.out.println("After a %= 3, a = " + a); //0
// Bitwise AND and assign
a &= 1; // Equivalent to: a = 0 & 1;
System.out.println("After a &= 1, a = " + a); //0
// Bitwise OR and assign
a |= 2; // Equivalent to: a = 0 | 2;
System.out.println("After a |= 2, a = " + a); //2
// Bitwise XOR and assign
a ^= 3; // Equivalent to: a = 2 ^ 3; 0010 ^ 0011 = 0001
System.out.println("After a ^= 3, a = " + a); //1
// Left shift and assign
a <<= 1; // Equivalent to: a = a << 1; 0010
System.out.println("After a <<= 1, a = " + a); //2
// Right shift and assign
a >>= 1; // Equivalent to: a = 2 >> 1; 0010 >> 0001
System.out.println("After a >>= 1, a = " + a); //1
}
}Result:
Watch the video:
Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

