Assignment operator is used to assigning a value to any variable. This operator assigns the value of the right–hand side of an operator to the left–hand side. Various assignment operator in Java:
These are the short version formed by combining the two operators.
For example Instead of writing, we can write a+= 5
.
- Assignment operator: ‘=’ This operator assigns the value on the right to the variable on the left.
a = 20; B = 30; Ch = 'cha';
- Add AND assignment operator: ‘+=’ This operator first adds the current value of the variable on the left to the value on the right and then assigns the result to the variable on the left.
c+=7; a+=b;
- Subtract AND assignment operator: ‘-=’ This operator first subtracts the current value of the variable on the left from the value on the right and then assigns the result to the variable on the left.
c-=7; a-=b;
- Multiply AND assignment operator: ‘*=’ This operator first multiplies the current value of the variable on the left to the value on the right and then assigns the result to the variable on the left.
c*=7; a*=b;
- Divide AND assignment operator: ‘/=’ This operator first divides the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left.
c/=7; a/=b;
- Modulus AND assignment operator: ‘%=’ It takes modulus using two operands and assigns the result to the left operand.
C %= A is equivalent to C = C % A ;
- Right shift AND assignment operator: ‘>>=’ This operator is used for Right shift Operation.
C >>= 2 ;
- Left shift AND assignment operator: ‘<<=’ This operator is used for Left shift Operation.
C <<= 2 ;
- Bitwise AND assignment operator: ‘&=’ This operator is used for Bitwise AND Operations.
C &= 2;
- Bitwise exclusive OR and assignment operator: ‘^= This operator is used for Bitwise exclusive OR Operations.
C ^= 2;
- Bitwise inclusive OR and assignment operator: ‘|= This operator is used for Bitwise inclusive OR.
C |= 2;
Example of Assignment Operator:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class AssignmentOperator { public static void main(String args[]) { int number1 = 100; int number2 = 10; number2 += number1; number2 -= number1; number2 *= number1; number2 /= number1; number2 %= number1; System.out.println(" Result of +=: "+number2); System.out.println(" Result of -=: "+number2); System.out.println(" Result of *=: "+number2); System.out.println(" Result of /=: "+number2); System.out.println(" Result of %=: "+number2); } } |
Output:
1 2 3 4 5 | Result of +=: 110 Result of -=: 90 Result of *=: 1000 Result of /=: 10 Result of %=: 0 |