Java Assignment Shortcuts


Collapse Content

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.

Increment Operator
Since adding and subtracting 1 are so common in programming, Java added the ++ and -- shortcut so you don't even need to type 1:

int count = 0;
count++; 

count is now 1.

count = 10;
count--;
count--;

count is now 8.

This shortcut is often used in for loops:

for(int i=0; i<10; i++){
  System.out.println(i);
} 
Extra Increment Operator

Challenge

What will the following code print out after executing?

int x, result, z;
x = 5;
result = z = x*2;
result *= 3;
result++;
z--;
result += z;
System.out.println(result);

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

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