This lesson covers short hand operators that help you write code more concisely.
While = is the most commonly known assignment operator, there are several other assignment operators in Java. These operators are +=, -=, and *=, which are also known as short-hand operators.
To understand this, let us take a variable called ‘a’, holding an initial value of 5. To increase the value of x by five units, the usual statement is:
a = a + 5;
The program assesses the expression on the right side of the “=” operator, a + 5, and assigns it to the left. Therefore, ‘a’ becomes 10.
However, instead of writing a = a + 5, a += 5 can be written to view the same result. The += assignment operator is a shorthand, wherein the assignment operator and the operator used to add two values are combined. Therefore, a += 5 also means a = a + 5.
In the same manner, to perform subtractions, either a = a – 3 or a -= 3 can be typed. This shorthand method is applicable for all the operators mentioned a while ago.
In the majority of programming languages, ++ and — operators are also valid. The use of ++ operator is to increase the value of the variable by 1. For example, when
int a = 6;
Turns the value of a to 7.
By using the ++ operator, you need not use the = operator. That is, the statement a++; can be equated to
a = a + 1;
Remember that ++ is different when placed behind the variable and in front of the variable. That is because its position impacts the order of the tasks performed.
For instance, let us take an integer with the variable name userAge. Now, write
The original value of userAge is printed before the number is increased by 1. To be even clearer, this is the order of tasks performed:
System.out.println(userAge); userAge = userAge + 1;
The variable age first increases by 1, and then the new value is printed. Therefore, it now executes the tasks in this specific order:
userAge = userAge + 1; System.out.println(userAge);
Apart from the ++ operator, the – operator is also present, which functions similarly. This operator decreases the variable by a value of 1.