Assignment Operator Java

Java Assignment Operators

Description

Assigning a value to a variable seems straightforward enough; you simply assign the stuff on the right side of the '= 'to the variable on the left. Below statement 1 assigning value 10 to variable x and statement 2 is creating String object called name and assigning value "Amit" to it.

Statement 1: x =10; Statement 2: String name = new String ("Amit");

Assignment can be of various types. Let’s discuss each in detail.

ads

Primitive Assignment:

The equal (=) sign is used for assigning a value to a variable. We can assign a primitive variable using a literal or the result of an expression.

int x = 7; // literal assignment int y = x + 2; // assignment with an expression int z = x * y; // assignment with an expression with literal

Primitive Casting

Casting lets you convert primitive values from one type to another. We need to provide casting when we are trying to assign higher precision primitive to lower precision primitive for example If we try to assign int variable (which is in the range of byte variable) to byte variable then the compiler will throw an exception called "possible loss of precision". Eclipse IDE will suggest the solution as well as shown below. To avoid such problem we should use type casting which will instruct compiler for type conversion.

byte v = (byte) a;

For cases where we try to assign smaller container variable to larger container variables we do not need of explicit casting. The compiler will take care of those type conversions. For example, we can assign byte variable or short variable to an int without any explicit casting.


Assigning Literal that is too large for a variable

When we try to assign a variable value which is too large (or out of range ) for a primitive variable then the compiler will throw exception “possible loss of precision” if we try to provide explicit cast then the compiler will accept it but narrowed down the value using two’s complement method. Let’s take an example of the byte which has 8-bit storage space and range -128 to 127. In below program we are trying to assign 129 literal value to byte primitive type which is out of range for byte so compiler converted it to -127 using two’s complement method. Refer link for two’s complement calculation (http://en.wikipedia.org/wiki/Two's_complement)

Java Code: Go to the editor

Output:


Reference variable assignment

We can assign newly created object to object reference variable as below

String s = new String(“Amit”); Employee e = New Employee();

First line will do following things,

  • Makes a reference variable named s of type String
  • Creates a new String object on the heap memory
  • Assigns the newly created String object to the reference variables

You can also assign null to an object reference variable, which simply means the variable is not referring to any object. The below statement creates space for the Employee reference variable (the bit holder for a reference value) but doesn't create an actual Employee object.

Employee a = null;

Compound Assignment Operators

Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as:

i +=8; //This is same as i = i+8;

The += is called the addition assignment operator. Other shorthand operators are shown below table

Operator NameExampleEquivalent
+=Addition assignment i+=5;i=i+5
-=Subtraction assignmentj-=10;j=j-10;
*=Multiplication assignment k*=2;k=k*2;
/=Division assignment x/=10;x=x/10;
%=Remainder assignment a%=4; a=a%4;

Below is the sample program explaining assignment operators:

Java Code: Go to the editor

Output:


Summary

  • Assigning a value to can be straight forward or casting.
  • If we assign the value which is out of range of variable type then 2’s complement is assigned.
  • Java supports shortcut/compound assignment operator.

Java Code Editor:

The assignment operator (=) is the most commonly used binary operator in Java. It evaluates the operand on the tight hand side and then assigns the resulting value to a variable on the left hand side. The right operand can be a variable, constant, function call or expression. The type of right operand must be type compatible with the left operand. The general form of representing assignment operator is

                       Variable = expression/constant/function call

                       a = 3; //constant

                       x = y + 10; //expression

In the first case, a literal value 3 is stored in the memory location allocated to variable a. In the second case, the value of expression y+ 10is evaluated and then stored in memory allocated to

variable x.

Consider a statement x = y = z = 3;

Such type of assignment statement in which a single value is given to a number of variables is called multiple assignment statement i.e. value 3 is assigned to the variables x, y and z. The assignment operator (=) has a right to left associatively, so the above expression is interpreted as

(x = (y = (z = 3)));

Here, first the value 3 is assigned to z, then value stored in z is assigned to y and then finally y is assigned to x. Now let us consider a statement

x = 3 = 5;

This type of statement is invalid assignment statement and it will generate an error.

\

There is another kind of assignment statement which combines a simple assignment operator with five arithmetic binary operators and six bitwise operators. This type of operator is known as compound assignment operator. The general syntax of compound assignment operator IS

                 Variable operator= expression/constant/function call

For example: Suppose i is a variable of type int then the statement,

i += 5;

will add the literal 5 to the variable i and store the result back into the variable i. The various compound assignment operators and their effect are as shown in table

Operator

Usage

Effect

+=

-=

*=

/=

%=

&=

|=

^=

<<=

>>=

>>>=

a+=b;

a-=b;

a*=b;

a/=b;

a%=b;

a&=b;

a|=b;

a^=b;

a<<=b;

a>>=b;

a>>>=b;

a=a+b;

a=a-b;

a=a*b;

a=a/b;

 a=a%b;

a=a&b;

a=a|b;

a=a^b;

 a=a<<b;

 a=a>>b;

    a=a>>>b;

Such operator makes the statement concise so they are also called shorthand assignment operator. The expression a = a+b is almost same as that of a += b but the mainadvantage of shorthand assignment operator is that the operand is that the operand on the left handside of the assignment is evaluated only once. The assignment operators have the lowestprecedence as compared to other operators. Only one variable is allowed on the left hand sideof the expression. Therefore a=x*y is valid and m*n=l is invalid.

It is to be kept in mind that assignment operator (=) and equality operator (= =) are different. The assignment operator is used to assign a value to a variable whereas the equality operator used to compare two operands. These operators cannot be used in place of each other. The assignment operator( =) has lower precedence than arithmetic, relational, bitwise, and logical operators.

Java Example to implement assignment operations
import java.util. *;
class AssignmentOperator
{
                  public static void main(String args[])
         {
                    int X=12, Y=13, Z=16;
                    System.out.println("The Assignment Value is : ");
                    X+=2;
                    Y-=2;
                    Z*=2;
                    System.out.println("The Value of X is : " +X);
                    System.out.println("The Value of Y is : " +Y);
                    System.out.println("The Value of Z is : " +Z);
          }
}

Java Example to perform assignment operations using Scanner Class.
import java.util. *;
class AssignmentOperator
{
                  public static void main(String args[])
         {
                    int X,Y;
                    Scanner scan=new Scanner(System.in);
                    System.out.print("Enter the Value of X : ");
                    X=scan.nextInt();
                    System.out.print("Enter the Value of b : ");
                    Y=scan.nextInt();
                    System.out.println("X += 6 : "+(X+=6));
                    System.out.println("X -= 4 : "+(X-=4));
                    System. out. println("Y *= 4 : "+(Y*=4));
                    System. out. println("Y /= 6 : " +(Y/=6));
          }
}



0 Thoughts to “Assignment Operator Java

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *