Java Theory - Increment and decrement
In this topic, we will discuss one of the most famous operations in programming: increment . It is used in many programming languages including Java to increase a variable by one. Fun fact: this operation is used in the name of C++, and signifies the evolutionary nature of the changes from C.
1. Using ++ and -- in Java
Java has two opposite operations called increment (++) and decrement (--) to increase/decrease the value of a variable by one.
int n = 10;
n++; // 11
n--; // 10
The code above is actually the same as below.
int n = 10;
n += 1; // 11
n -= 1; // 102. Prefix and postfix forms
Both increment and decrement operators have two forms which are very important when using the result in the current statement:
- prefix (
++nor--n) increases/decreases the value of a variable before it is used;- postfix (
n++orn--) increases/decreases the value of a variable after it is used.The following examples demonstrate both forms of increment.
Prefix increment:
int a = 4;
int b = ++a;
System.out.println(a); // 5
System.out.println(b); // 5In this case, the value of
ahas been incremented and then assigned tob. So,bis 5.Postfix increment:
int a = 4;
int b = a++;
System.out.println(a); // 5
System.out.println(b); // 4In Java, the postfix operator has higher precedence than the assignment operator. However, it returns the original value of
a, not the incremented one. That's why when we assigna++tob, we actually assign 4, whileaitself has already been incremented. So,bis 4 andais 5.
If that's still not clear enough for you, take a look at the code:
int a = 4;
System.out.println(a++ + a); // this is 9
I hope that now you fully understand increment and decrement and their prefix and postfix forms.

Comments
Post a Comment
Wow nice post!