Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Master-java Assignment operator in java

Related Tutorials


 
 

Share on Google+Share on Google+

Assignment operator in java

Advertisement
This tutorial will help you to understand assignment operator in java.

Assignment operator in java

Assignment operator is very common to almost all programming languages. It is represented as "=" symbol which assign the value to the variable lying on the left side. Java assignment operator evaluated from right to left, in the right side is the value which have to be assigned to the variable to the left side. Assignment operator is also used to assign object reference. Java allow to use shorthand means combining the assignment operator with the arithmetic operator. It is called compound assignment.  In the table below showing shorthand operator:

Syntax : <variable> = <expression or constant>

Example :

public class Demo 
 {
  public static void main(String args])
   {
    int a=b=c=2;
    int result=0;
    result = a + b;
    c = a + b;
    System.out.println("Value of result = " +result);
    System.out.println("Value of c = "+c);
     }
    } 

The above example show the uses of assignment operator,  You can also assign a value to three variable simultaneously. How it works is,  value 2 is assigned to c, then c to b. then b to a. In second expression value of a and b is added and then assigned to c.

The table show all short hand operator:

OperatorExampleEquivalent expression
+=a+=1a=a+1
-=a-=1a=a-1
*=a*=1a=a*1
/=a/=1a=a/1
%=a%=1a=a%1

A simple example using compound assignment:

public class Assignment {
	public static void main(String args[])
	{
		int a=2;
		int b=3;
		
		a+=b;
		System.out.println("value of a after addition is ="+a);
		a-=b;
		System.out.println("value of a after subtraction = "+a);
	     
		a*=b;
		System.out.println("value of a after multiplication = "+a);
	     
		a/=b;
		System.out.println("value of a after division = "+a);
	     	}

}

Output of the program

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 19, 2013

Related Tutorials

Discuss: Assignment operator in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com