Arithmetic Assignment operators in Java


The five arithmetic assignment operators are a form of short hand. Various textbooks call them "compound assignment operators" or "combined assignment operators". Their usage can be explaned in terms of the assignment operator and the arithmetic operators.

Compound OperatorSample ExpressionExpanded Form
+= x+=2 x=x+2
-= y -=6 y=y-6
*= z *=7 z=z*7
/= a /=4 a=a/4
%= b %=9 b= b%9

This Java program defines a class called Assignment which contains a main() method that performs arithmetic operations using assignment operators on an integer variable a. The program prints the value of a after each operation using System.out.println() method. Here is the breakdown of the operations performed in the program:

  • Initialization: The integer variable a is initialized with a value of 123.
  • Printing: The value of a is printed to the console using System.out.println() method.
  • Addition Assignment: The += operator is used to add 10 to the value of a. The result is assigned to a. The updated value of a is printed using System.out.println() method.
  • Subtraction Assignment: The -= operator is used to subtract 10 from the value of a. The result is assigned to a. The updated value of a is printed using System.out.println() method.
  • Multiplication Assignment: The *= operator is used to multiply the value of a by 10. The result is assigned to a. The updated value of a is printed using System.out.println() method.
  • Division Assignment: The /= operator is used to divide the value of a by 10. The result is assigned to a. The updated value of a is printed using System.out.println() method.
  • Modulus Assignment: The %= operator is used to calculate the remainder when a is divided by 10. The result is assigned to a. The updated value of a is printed using System.out.println() method.

Source Code

public class Assignment
{
    public static void main(String args[])
    {
        int a=123;
        System.out.println(a);
        a+=10;
        System.out.println(a);
        a-=10;//a=a-10
        System.out.println(a);
        a*=10;
        System.out.println(a);
        a/=10;
        System.out.println(a);
        a%=10;
        System.out.println(a);
    }
}
 

Output

123
133
123
1230
123
3
To download raw file Click Here

Basic Programs