Java 8 | Increment / Decrement Operator

Student Kim
Buzz Code
Published in
3 min readJan 11, 2021

--

Hi guys! I know last time I told you that I’m going to talk about the two dimensional array this time, but I thought it’d be better to know the concept of the whole increment/decrement operator first, before we go too far. So let’s get this started! And don’t forget to checkout my old post about the operators!

Like I said in my old post, there are unary operator, which look like a++ , a-- , ++a , --a . But last time I told you both a++ and ++a mean a=a+1 , also a--, --a mean a=a-1 . Today I’ll finally explain what’s the differences.

[Pre-Increment & Pre-Decrement Operators]

So when the unary operator is in front of the variable ++a /--a, we call it as pre-increment/decrement operator. And it changes the value of the variable first, and use the new variable on the line of the code. For instance,

Let’s say I declared the variable a into 10 like above. And then if I printed the ++a, It changed a’s value into 11 first, and then operated the println() method with the new value, so it printed 11. Same with the pre-decrement operator here, it changed a’s value back to 10, and print it out.

[Post-Increment & Post-Decrement]

Let’s see the example of the Post-Increment/Decrement Operators too.

As you see, I printed a++ on the line 10, and it printed the number 10 out which is the initial value of the variable a , and then I printed the a again, it printed the increased number! So it uses the old value on the println() first, and then changes its value! And it also works the same on the post-decrement as well.

It can be a bit confusing, so I brought you some of the practice questions!

[Question] What’s the right answers on below?

int a = 24;System.out.println("1) " + ++a);  ->  1) ?
System.out.println("2) " + a--); -> 2) ?
System.out.println("3) " + --a); -> 3) ?
System.out.println("4) " + a++); -> 4) ?

This time, let’s solve only with our eyes and hands, without using eclipse.

The answer is on below.

So the answer of the 1) is 25, cause it’s pre-increment, so it increases the value first then it prints the new value out. And on the 2) the a’s old value is printed out first, and then decreases the value. So after the 2) printed out, the a becomes 24, and on the 3) decreases the value again, and prints. So 3) is 23. And on the 4) it prints the value first then gets one bigger! So If I print a again after the 4) it will be 24.

So that’s all for today guys, it seemed to be complicated, but turns out it wasn’t right? Next time I’ll definitely talk about the Two Dimensional Array for sure. Well done today as well! See ya!

--

--