Understanding Java Assignment Operators

In Java, assignment operators are used to assign values to variables. They also allow for combining an operation with assignment, making it concise to perform an operation on a variable and assign the result back to the same variable.

Assignment Operators:

  • = Assignment: Assigns the value of the right operand to the left operand.
  • += Addition Assignment: Adds the value of the right operand to the left operand.
  • -= Subtraction Assignment: Subtracts the value of the right operand from the left operand.
  • *= Multiplication Assignment: Multiplies the left operand by the value of the right operand.
  • /= Division Assignment: Divides the left operand by the value of the right operand.
  • %= Modulus Assignment: Assigns the remainder of the division of the left operand by the value of the right operand.
  • &= Bitwise AND Assignment: Performs bitwise AND between the left operand and the right operand, and assigns the result to the left operand.
  • |= Bitwise OR Assignment: Performs bitwise OR between the left operand and the right operand, and assigns the result to the left operand.
  • ^= Bitwise XOR Assignment: Performs bitwise XOR between the left operand and the right operand, and assigns the result to the left operand.
  • <<= Left Shift Assignment: Shifts the bits of the left operand to the left by a specified number of positions, and assigns the result to the left operand.
  • >>= Right Shift Assignment: Shifts the bits of the left operand to the right by a specified number of positions, and assigns the result to the left operand.
  • >>>= Unsigned Right Shift Assignment: Shifts the bits of the left operand to the right by a specified number of positions, filling the vacant positions with zeros, and assigns the result to the left operand.

Examples:

Here are examples of using assignment operators in Java:


int a = 5;

// Assignment
int b = a; // b is now 5

// Addition Assignment
a += 3; // a is now 8

// Subtraction Assignment
a -= 2; // a is now 6

// Multiplication Assignment
a *= 4; // a is now 24

// Division Assignment
a /= 3; // a is now 8

// Modulus Assignment
a %= 5; // a is now 3

// Bitwise AND Assignment
a &= 1; // a is now 1

// Bitwise OR Assignment
a |= 2; // a is now 3

// Bitwise XOR Assignment
a ^= 3; // a is now 0

// Left Shift Assignment
a <<= 2; // a is now 0

// Right Shift Assignment
a >>= 1; // a is now 0

// Unsigned Right Shift Assignment
a >>>= 1; // a is now 0

Note:

Assignment operators are essential for assigning values and updating variables in Java. They provide a concise way to perform operations and assignments in a single step.