Java Assignment Operators

Java has several assignment operators that are used to assign values to variables. The basic assignment operator in Java is the equal sign (=), which assigns the value on the right side of the operator to the variable on the left side. Here are some examples:


 int x = 10; double y = 20.5; String name = "John Doe";


Aside from the basic assignment operator, Java also has a set of compound assignment operators that allow you to perform an operation and an assignment in a single statement. Here are some of the most commonly used compound assignment operators in Java:


  • +=: Adds the right-side value to the left-side variable and then assigns the result to the left-side variable.

 int x = 10; x += 5; // x is now 15

  • -=: Subtracts the right-side value from the left-side variable and then assigns the result to the left-side variable.

int x = 10;
x -= 5; // x is now 5

  • *=: Multiplies the left-side variable by the right-side value and then assigns the result to the left-side variable.

int x = 10;
x *= 5; // x is now 50

  • /=: Divides the left-side variable by the right-side value and then assigns the result to the left-side variable.

int x = 10;
x /= 5; // x is now 2


  • %=: Computes the remainder when the left-side variable is divided by the right-side value and then assigns the result to the left-side variable.

int x = 10;
x %= 3; // x is now 1

These are some of the most commonly used assignment operators in Java