Assignment Operators

Read this introductory article.

Simple Assignment Operator

The assignment statement is one of the central constructs in programming languages. Using an assignment statement, the programmer can change the binding of values to the variables in the program. In the simple assignment statements listed below, variables x and y are being assigned values 0 and 1 respectively. The variables are of type integer in this case.

int x = 0;
int y = 1;


Compound Assignment Operators

The assignment operator can be combined with various arithmetic and logic operators to provide compound assignments where arithmetic and logic operations are part of the assignment operation. The assignment can be combined with the following arithmetic and logic operations (the variable x is of type integer, z is a Boolean vector, and y is of type Boolean in these examples).




x += 5; or x = x+5




x -= 5; or x = x-5




x *= 5; or x = x*5




x /= 5; or x = x/5




x %= 5; or x = x%5


shift left


z <<= 5; or z<<5


shift right


z >>= 5; or z = z>>5




y &= 5; or y = y&5




y ^= 5; or y = y^5




y |= 5; or y = y|5


Unary Assignment Operators

Java has two special unary arithmetic operators, which are special cases of compound assignment operators. These are the increment and the decrement operators. They combine increment and decrement operations (++ and --) with the assignment operation. For example:

x = ++count;

is equivalent to

count = count + 1;
x = count;


Assignment for Object Creation

In object-oriented programming, classes provide a blueprint or a factory for creating objects. An object is an instance of a class. Using the new operation in Java, a programmer can create an instance of an object using the simple assignment operator. For example, if we have a rectangle class that uses length and width attributes, then:

rectangle R1 = new Rectangle(5, 10);

creates a new rectangle object named R1 with length 5 and width 10.

rectangle R2 = new Rectangle(7, 8);

creates another new rectangle object named R2 with length 7 and width 8.


Source: Saylor Academy
Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 License.

Last modified: Wednesday, April 17, 2019, 6:57 PM