Java Assignment Shortcuts
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);
}
Prefix and Postfix
The above shortcut is known as the postfix operator. There's another form of the above shortcut, which is known as the prefix operator: ++i
. Both the prefix and postfix operator will increment the variable, so usually there's no difference between them. However, if you use the operator as part of a larger expression, there's a difference: the prefix operator will increment the value for the current expression, while the postfix operator will only increment it afterwards:
public static void printNums() {
int i = 1;
i++;
System.out.println(i); //prints 2
++i; //no difference yet
System.out.println(i); //prints 3
System.out.println(++i); //prints 4 (prefix)
System.out.println(i++); //prints 4 (postfix)
System.out.println(i); //prints 5
}
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.