Assignment operators
- In Java assignment operators are used to assign values to variables.
- In this lesson we will discuss following assignment operators.
Operator | Explanation |
---|---|
== | This operator is commonly used to assign values on the right side to the variable on the left side. |
+= | This operator adds the numerical value on the left side to the variable on the right side and assigns the resulting value to the variable on the left side. |
This operator subtracts the numerical value on the left side from the variable on the right side and assigns the resulting value to the variable on the left side. | |
*= | This multiplies the value in the variable of the left side from the value on the right side and assigns the resulting value to the variable in the left side. |
/= | This divides the value of the variable on the left side from the value on the right side and assigns the resulting value to the left side variable. |
- +=, “”, *= and /= operators are similar to following scenarios.
i += 1;
// Is similar to ↓
i = i + 1;
i = 1;
// Is similar to ↓
i = i - 1;
i *= 2;
// Is similar to ↓
i = i * 2;
i /= 2;
// Is similar to ↓
i = i / 2;
- Also assignment operators can be used to create a chain of assignments.
- That means we can assign a single value for multiple variables simultaneously.
E.g.:
a = b = c = 10;
Which of the following can be used instead of “i = i * 2”.