Java arithmetic compound operator
Arithmetic Compound Assignment Operators in Java
In the previous two tutorials we have used Arithmetic and Assignment Operators.In this Article we are going to combine Assignment as well as Arithmetic Operators together.
Consider General traditional Syntax -
num1 = num1 + 2
Now after using arithmetic Compound Assignment Statement , Equivalent Statement for above statement is -
num1 += 2
How To Remember This Type of Statement ?
Step 1 : Write Statement As it is. (With using Arithmetic Operator inside Two Operands)
Step 2 : Write Arithmetic Operator before Assignment Sign.
Step 3 : Remove First Operand which is same as “Left Value”.
Step 4 : We will get Arithmetic Compound Assignment Statement Expression.
[468x60]
Live Example : Arithmetic Compound Assignment Operators in Java
class CompoundAssignmentDemo { public static void main(String args[]) { int a = 1; int b = 2; int c = 3; a += 1; b *= 1; c %= 1; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); } }[468x60]
Output :
a = 2 b = 2 c = 0
Live Example 2 : Another Operation With Compound Assignment
class CompoundAssignmentDemo { public static void main(String args[]) { int a = 1; int b = 2; int c = 3; a += b * c; System.out.println("a = " + a); } }
Output :
a = 7
Explanation :
- We have used multiplication Operator inside Expression.
- Multiplication Operator have High Priority than Compound Assignment. [See Precedence Chart]
- It will be executed first and after completing multiplication , Value is Added with “a”.
Examples : Arithmetic Compound Assignment Operators
Operator | Use of Operator |
---|---|
n1 += 2 | n1 = n1 + 2 |
n1 -= 2 | n1 = n1 - 2 |
n1 *= 2 | n1 = n1 * 2 |
n1 /= 2 | n1 = n1 / 2 |
n1 %= 2 | n1 = n1 % 2 |