Java: Assignment Operator

The assignment operator in java does the job of assigning values to the variable.

  • The left side is the variable that will be followed by the operator and the operand which is on the right side.
  • The values on the right must be of the same datatype as of the left else it will throw compile error.
  • So basically it has the right to left associativity thus the value must be declared on the left side or should be made as constant.

So let's take a look at the different types of assignment operators that exist in the java programming language.

1) =

So this is the basic assignment operator that assigns the value to the left and points out that the operand which is assigning to that variable is the particular one on the right.

Syntax

val1 = val2

2) +=

This operator is a mix of + and = which will do the basic addition of the left variable with the right operand value and then assigns the final value to the left variable.

Syntax

val1 += val2

which also means

val1 = val1 + val2

3) -=

This operator is a mix of - and = which will do the basic subtraction of the left variable with the right operand value and then assigns the final value to the left variable.

Syntax

val1 -= val2

which also means

val1 = val1 - val2

4) *=

This operator is a mix of * and = which will do the basic multiplication of the left variable with the right operand value and then assigns the final value to the left variable.

Syntax

val1 *= val2

which also means

val1 = val1 * val2

5) /=

This operator is a mix of / and = which will do the basic division of the left variable with the right operand value and then assigns the final value to the left variable.

Syntax

val1 /= val2

which also means

val1 = val1 / val2

6) %=

This operator is a mix of % and = which will do the basic division of the left variable with the right operand value and then assigns the final leftover value/remainder to the left variable.

Syntax

val1 %= val2

which also means

val1 = val1 % val2

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 10 , val2 = 20;  //= Operator

        val1 += val2;
        System.out.println(val1);

        val1 -= val2;
        System.out.println(val1);

        val1 *= val2;
        System.out.println(val1);

        val1 /= val2;
        System.out.println(val1);

        val1 %= val2;
        System.out.println(val1);
    }
}

Output:

30
10
200
10
10
Tue, 10/12/2021 - 12:34

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags