Sunday, July 11, 2010

Java Assignment Operators

It's very common to see statement like the following, where you're adding something to a variable. Java Variables are assigned, or given, values using one of the assignment operators. The variable are always on the left-hand side of the assignment operator and the value to be assigned is always on the right-hand side of the assignment operator. The assignment operator is evaluated fromright to left, so a = b = c = 0; would assign 0 to c, then c to b then b to a.


i = i + 2;

Here we say that we are assigning i's value to the new value which is i+2. 

A shortcut way to write assignments like this is to use the += operator. It's one operator symbol so don't put blanks between the + and =. 
i += 2; // Same as "i = i + 2"

The shortcut assignment operator can be used for all Arithmetic Operators i.e. You can use this style with all arithmetic operators (+, -, *, /, and even %).


Here are some examples of assignments:

//assign 1 to 
//variable a
int a = 1;

//assign the result 
//of 2 + 2 to b
int b = 2 + 2;

//assign the literal 
//"Hello" to str
String str = new String("Hello");

//assign b to a, then assign a 
//to d; results in d, a, and b being equal
int d = a = b;


--
http://www.co5.in/

0 comments:

Post a Comment

 

Complete Online Solution | Make the internet world into your hands Copyright © 2009 Community is Designed by CO5 | Web designing | Web hosting