Java From Beginner To Advanced

0% completed

Previous
Next
Assignment operators

Assignment operators are used to assign values to variables in Java. Besides the basic assignment operator (=), Java provides compound assignment operators that combine an arithmetic operation with assignment. These operators simplify your code and improve readability.

Assignment Operators

OperatorDescriptionExample
=Assigns the value on the right to the variable on the lefta = 10
+=Adds the right operand to the variable and assigns the result to the variablea += 5 (equivalent to a = a + 5)
-=Subtracts the right operand from the variable and assigns the resulta -= 3 (equivalent to a = a - 3)
*=Multiplies the variable by the right operand and assigns the resulta *= 2 (equivalent to a = a * 2)
/=Divides the variable by the right operand and assigns the resulta /= 4 (equivalent to a = a / 4)
%=Applies modulus on the variable by the right operand and assigns the resulta %= 3 (equivalent to a = a % 3)

Example 1: Using Basic and Compound Assignment Operators

Below is an example that demonstrates the use of the basic assignment operator as well as compound assignment operators.

Java
Java

. . . .

Explanation:

  • Basic Assignment (=): The variable a is initially assigned the value 10.
  • Addition Assignment (+=): The value 5 is added to a, updating it to 15.
  • Subtraction Assignment (-=): The value 3 is subtracted from a, updating it to 12.
  • Multiplication Assignment (*=): The value a is multiplied by 2, updating it to 24.
  • Division Assignment (/=): The variable a is divided by 4, updating it to 6.
  • Modulus Assignment (%=): The remainder when a is divided by 4 is assigned back to a, updating it to 2.

These examples demonstrate how assignment operators allow you to update variable values succinctly. By using compound operators, you can write cleaner and more efficient code.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next