Hi! My name is Narendra Vardi, and I write about my learnings, observations and trends in the Software world. Besides software, I also talk about photography, travel stories, books and movies. If that's something that interests you, consider subscribing.
Before we get into the details of the article, let me ask you a question.
Can you tell me what will be the output of following program?
It's fairly easy one right?
The output must be the following, correct?
Now, let's take one more sample code. What will be the output of following program?
It's fairly easy but also a tricky one isn't it?
So, the output is:
Now if you understood this output, you can stop reading this article! (Having said that you can share some feedback on how the article is provided that you know the concepts 😄)
If you didn't understand this output, let me tell you what's happening.
When we are taught these operators in colleges or beginner books, the first example they would give is using these operators as a single statement.
a++; // single statement ++a; // single statement
Because of the way it is used, we only see
++ as a increment operator and we don't really focus on whats the difference between
Now when we combine
a++ with other operators (or used in methods as Example #2), we will get to know the difference.
So, what's the major difference?
Before we get into the differences, lets see what's the increment operator doing.
What's the increment operator?
Increment operator has two functionalities.
- It increments the value of the variable and
- It returns a value (What value - we will talk about it)
Now talking about
It increments the value of the variable functionality, this is same for
a value will be incremented by
1 in both the usages.
The major difference is observed with the second functionality,
It returns a value
++a-> returns incremented value where as
a++-> returns the value and does the increment later.
And that's the reason why
System.out.println(++a); returned 3 when a was initially 2 but
System.out.println(a++); remained 2.
To clarify even better, I wrote a Java class that helps us visualise the work of Pre and Post Increment Operators.
Here's the code for the same. Take a look at it and let me know what you think!
Finally, let's see how the
example #2 looks using the increment class that I have written.
With the provided examples, were you able to identify clearly understand what's the difference between Pre and Post Increment Operators?
Can you write the classes for Decrement operators as well? Please feel free to comment below or shoot an email.
Share this article
Copy and share this article: narendravardi.com/pre-post-increment/
If you liked this article, you might also enjoy reading the following.
- 🤩How to write extensible filter logic in Java code
- 🤖Automating the boring stuff: How I obtained the titles of all articles on my blog
- Future Software Engineers, read this article before and during your placements
❤️ Enjoyed this article?