Showing posts with label java assignment operator. Show all posts
Showing posts with label java assignment operator. Show all posts

Thursday, 28 May 2015

Java Assignment Operator (=)

The assignment operator has the following syntax:

<variable> = <expression>

Here variable can be of primitive type or reference type. Similarly expression may result in a primitive data value or object reference:

Example: Assignment involving primitives.

x = 10;

Example: Assignment involving reference data type.

int x[];

x = new int [100];

Here new is an operator that returns an object reference.

Multiple Assignments

The assignment operator = may be used like any other operator to form a compound expression.

The operator can appear more than once in an assignment statement as shown below:

Example:

int x = 5, y = 6 , z = 7;

x = y = z; //multiple assignment statement

Here = behaves like an operator. It is a right associative operator, hence after the execution of the assignment statement, the value of variables x, y and z will be 7.

Example:

int  x[], y[];

x = y = new int[20];

Here new operator returns reference to an array, which can hold 20 int values. The reference is first assigned to y and then to x as the = operator is right associative.

Note: Assigning a reference does not create a copy of the object. So both x and y refer to the same array in this example.