04.03. Assignment Operators

Assignment Operators

  • Eclipse: Oxygen
  • Java: 1.8

Assignment operators are a binary operator that is used to assign a value of an expression to a variable on the left-hand side of the operator, with the result of the value on the right-hand side of the equation.

In Java, the assignment operator are: =,+=,-+,*=,/=,%=

There are following assignment operators list supported by java programming language

Operator Description Example Type of operation
= Simple assignment operator, Assigns values from right side operands to left side operand X=5 Binary
+= Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand X+=5 Binary
-= Subtract AND assignment operator, It subtracts the right operand from the left operand and assigns the result to left operand X-=5 Binary
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assigns the result to left operand x*= 5 Binary
/= Divide AND assignment operator, It divides the left operand with the right operand and assigns the result to left operand x /= 5 Binary
%= Modulus AND assignment operator, It takes modulus using two operands and assigns the result to left operand x %= 5 Binary

 

The simplest assignment operator is “=” assignment (int x= 1 ;). Which you have seen already.

Explanation

int x = 5;

This statement assigns x the value of 5.

Compound assignment operator in java

Besides the simple assignment operator”=” there are also various compound assignment operator. For example, the following statement after the declaration of x is equivalent:

x += 5;   // simple assignment operator

x = x+5; // compound assignment operator

x -= 5;   // simple assignment operator

x = x-5; // compound assignment operator

x*= 5;// simple assignment operator

x = x*5; // compound assignment operator

x /= 5; // simple assignment operator

x / 5; // compound assignment operator

x %= 5; // simple assignment operator

x = x%5;// compound assignment operator

Explanation

In the below statement we are using compound assignment operator. Here int x=5 is initialization of value and x+=5 is a compound assignment operator and equivalent to x=x+5, we will get the result as 10.

Output: 10

In this statement, we are using compound assignment operator x-=5, the equivalent to x=x-5 and we will get the result as 5.

Output: 5

In this statement compound assignment is x*=5; the equivalent to x=x*5. We will get the result as 25.

Output: 25

In this statement compound assignment operator is x /= 5; the equivalent to x=x/5 and we will get the result as 1.

 Output: 1

In this statement compound assignment is x %= 5; and the equivalent to x=x%5 and we will get result as 0 which is remainder of this operator.

Output: 0

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments