1
0

Assignment Operator in Java

One of the most common operators that you will encounter is the simple assignment operator “=”. You saw this operator in all programs discussed so far; it assigns the value of the right-hand side expression to the variable on its left:

int a = 0;
int b = a + 1;
int c = a * b - 5;

The assignment operators can be used in different ways:

Simple Assignment:

The simple assignment statement is the most frequently used statement in general programs. This statement has the following syntax:

variable = expression;

Here the type of the left-side variable must match the type of the result of the right-side expression. The expression on the right-hand side can be constant, variable, or expression. Examples of simple assignments are:

a = 5;
b = a + 5;
c = a * b;

Multiple Assignment:

The multiple assignment statement has the following syntax:

variable1 = variable2 = ... = variableN = expression;

Here all the variables are of the same type and the result of an expression is assigned to all the variables. For example:

a = b = c = 10;

In this example, the variables a, b, and c are assigned the same value of 10.

Operator Assignment:

The operator assignment operator combines the binary operator with the assignment operator. The syntax of the operator assignment statement is:

variable op = expression;

Here op is one of the binary operators. This statement is equivalent to a simple assignment statement written as:

variable = variable op expression;

For example, the simple assignment statement a = a + 4 can be written as an operator assignment statement as a += 4;

This version used the += assignment operator. Both statements perform the same action: they increase the value of a by 4.

Here is another example,

Program to demonstrate assignment operators.

class AssignmentOperators
{
    public static void main(String args[])
    {
        int a= 1;
        int b = 2;
        int c = 3;
        a += 5; // a = a + 5;
        b *= 4; // b = b * 4;
        c += a * b; // c = c + a * b;
        c %= 6; // c = c % 6;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
        
    }
}

The output of this program is shown here:

a = 6
b = 8
c = 3

This operator can also be used on objects to assign object references, as discussed in Creating Objects.

Leave a Reply