Java Assignment Shortcuts


Premium Content - Free Preview

There are shortcuts in Java that let you type a little less code without introducing any new control structures.

Declaring and Assigning Variables
You can declare multiple variables of the same type in one line of code:

int a, b, c;

You can also assign multiple variables to one value:

a = b = c = 5;

This code will set c to 5 and then set b to the value of c and finally a to the value of b.

Changing a variable
One of the most common operations in Java is to assign a new value to a variable based on its current value. For example:

int index = 0;
index = index + 1; 

Since this is so common, Java let's you shorten it with a combined += operator that lets you skip the variable repetition:

index += 1;

(Note: Do not confuse this with index =+ 1; which would just assign positive 1 to index.)

In fact, any of the arithmetic operators can be used in this way:

            //j value
int j = 3; // 3
j *= 4;   // 12
j -= 2;  // 10
j /= 2; //  5

j started at 3 and ended up at 5 after the above operations.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Contact Us
Sign in or email us at [email protected]