Tuesday, July 3, 2012

JAVA Basics 6: 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 from right 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;

No comments:

Post a Comment