Assignment operators in java

Let’s learn assignment operators in java.

Assignment operators in java

Assignment operators are used to assign some value to variable. It’s a combination of left and right hand side value.

Left hand side of assignment operator should be a variable and right hand side is an expression which evaluates to value. For example,

int b = 6;
int a = 5 + 1;    // 5 + 1 is evaluated and value is stored in a

Here is the list of assignment operators,

“=” : This is the simplest assignment operator which is used to assign value to the variable on left hand side. Let’s see an example,

class AssignmentOperatorDemo 
{
   public static void main(String[] args) 
   {
      int num = 15;
      System.out.println(num);
   }
}

Output:

15


Chained assignment operator: here value to more than one variable is assigned in a single line.

int x, y, z;
x = y = z = 15;
System.out.println(x + "..." + y + "..." + z);

Output:

15…15…15


Compound assignment operator: is a combination assignment operator and another operator.

Here are various compound assignment operators: +=, -=, *=, /=, %=

“+=” :

class AssignmentOperatorDemo 
{
   public static void main(String[] args) 
   {
      int a = 7, b = 16;
      System.out.println("a = " + a);
      System.out.println("b = " + b);
      a += b; // a = a + b
      System.out.println("a = " + a);
   }
}

Output:

a = 7
b = 16
a = 23


“-=” :

class AssignmentOperatorDemo 
{
   public static void main(String[] args) 
   {
      int a = 7, b = 16;
      System.out.println("a = " + a);
      System.out.println("b = " + b);
      a -= b; // a = a - b
      System.out.println("a = " + a);
   }
}

Output:

a = 7
b = 16
a = -9


“*=” :

class AssignmentOperatorDemo 
{
   public static void main(String[] args) 
   {
      int a = 7, b = 16;
      System.out.println("a = " + a);
      System.out.println("b = " + b);
      a *= b; // a = a * b
      System.out.println("a = " + a);
   }
}

Output:

a = 7
b = 16
a = 112


“/=” :

class AssignmentOperatorDemo 
{
   public static void main(String[] args) 
   {
      int a = 21, b = 7;
      System.out.println("a = " + a);
      System.out.println("b = " + b);
      a /= b; // a = a / 7
      System.out.println("a = " + a);
   }
}

Output:

a = 21
b = 7
a = 3


“%=”:

class AssignmentOperatorDemo 
{
   public static void main(String[] args) 
   {
      int a = 21, b = 7;
      System.out.println("a = " + a);
      System.out.println("b = " + b);
      a %= b; // a = a % 7
      System.out.println("a = " + a);
   }
}

Output:

a = 21
b = 7
a = 0