DEV Community

Cover image for The Behavior of `i = i++` in Java
Jeremy Grifski
Jeremy Grifski

Posted on • Originally published at on

The Behavior of `i = i++` in Java

A little while back, I was running a Java lab, and one of my students had asked me why their code wasn’t working. As I glanced over their solution, I noticed a peculiar line that read i = i++. Up until that point, I had never seen any code like it, and I certainly had never tried it. So, I did what any good teacher would do and took to Google to find out more.

Java Loops

As someone who has written a bit of Java learning material, I consider myself at the very least proficient in the language. However, as I continue to teach, I find that students always come up with creative ways to stretch the language.

In my recent attempt to teach loops, I stumbled up a student solution that had the following while loop syntax:

int i = 0;
while (i < 10) {
  i = i++;
Enter fullscreen mode Exit fullscreen mode

Perhaps this odd bit of code was my fault. After all, I often tell my students that there are many ways to solve a problem.

To aid in that message, I like to switch up my syntax every now and then. For instance, it’s not uncommon for me to share solutions to looping problems using a different loop syntax each time. Sometimes I’ll use a for loop while other times I’ll use a while loop. If I’m feeling good, I might even show off a for each loop. Every once in a while I’ll even throw in some recursion to shake things up, but you’ll never catch me dead using a do while loop.

At any rate, this mentality shows up when I increment variables as well. For example, I tend to teach i = i + 1 first because it trips students up who haven’t recognized that the equal sign is really the assignment operator. Of course, once I think they’ve grasped the concept, I usually resort to shorthand like i++ and i += 1.

Unfortunately, my push for self-expression can sometimes result in mangled syntax like:

int i = 0;
while (i < 10) {
  // Do something
} else {
  // Do something else
Enter fullscreen mode Exit fullscreen mode

Every time I see something like this I feel like I move one step closer to overcoming the curse of knowledge. Enter: i = i++.

Java Increment Operators

As I mentioned already, there are a lot of ways to increment a variable in Java. The following list covers quite a few examples—albeit some are silly:

i = i + 1;
i += 1;
i = i - -1;
i -= -1;
i = -(~i)
Enter fullscreen mode Exit fullscreen mode

Despite all the options above, I’d never thought to try i = i++, yet it makes a lot of sense. After all, it looks like we increment the variable and store the result. To be honest, I was little perplexed when I saw it live in the lab.

As it turns out, i = i++ doesn’t work as expected, and it has to do with how the right side of the assignment statement is evaluated. Since i++ is a postfix operator, i is incremented but its old value is returned. As a result, i overwrites itself with the old value.

If the explanation above isn’t great, try taking a look at the following code snippet which replicates the behavior:

int temp = i;
i = temp;
Enter fullscreen mode Exit fullscreen mode

If we used the i = i++ syntax in a loop, we’d have an infinite loop on our hands with little at our disposal to diagnose the bug. Thankfully, I was there to at least recognize the issue. Whether or not I actually understood the bug was a separate problem, but I’m sure I saved that student a lot of time. Now, I hope to share my findings with others!

The Take Home

At this point in the series, I’m starting to notice a trend:

  • A student writes some interesting code
  • It does/n’t work to my surprise
  • I spend some time perplexed
  • I write an article to discuss my findings

Whether its fighting with the Scanner API or discovering new ways to play Rock Paper Scissors, I’ve got to say that I’m having a lot of fun learning from my students. I absolutely cannot wait to become a professor.

In the meantime, I’ll continue to document all the fun I’m having while teaching. If you’re enjoying my work, consider subscribing. If you’re already subscribed, you can help spread the word by sharing this article with people you know.

At any rate, thanks again for taking the time to support my work.

Discussion (8)

elmuerte profile image
Michiel Hendriks

I prefer to use ++i for most cases. As it does one thing instead of two.

My loops always have a ++i incrementor. Even though it does not make much difference. Usually the needless stack operation you get with i++ is optimized away. So there is no performance impact.

jakebman profile image

This is definitely a good habit in C++, where you can overload ++i and i++.

If you are using a custom type, i++ is required to return a temporary object representing the old state of the object, whereas ++i is allowed to 'increment' the i object and return the same object.

Compilers might be able to figure this out, but it's better to not make them do so.

jorgecc profile image
Jorge Castro

As a computer coach, I usually teach i++ inside the for-loop and nowhere else. i++ it's not as intuitive while i=i+1 it's more natural but it is common to see a code that uses i++ inside a "for" instead of i=i+1

Also, a novice could learn at most, a single for-loop cycle so it's shocking when some basic books and courses try to teach "bubble sort", it is hard to understand (for even seasoned developers) so it is more cruelty than teaching.

So, if a novice learns this 3 types of cycles, then it is more than enough:




renegadecoder94 profile image
Jeremy Grifski Author • Edited on

I’m not sure any of the increment operations are natural. i = i + 1 isn’t valid in math, so there’s a bit of a hurdle there. That said, if you teach i++ in the context of loops, I wouldn’t be surprised if you saw students mixing the syntax anyway.

I’m not a huge fan of teaching syntax and algorithms. I’d rather students develop the critical thinking skills to solve problems on paper. Transferring their thoughts to syntax should be the easy part (but something that takes practice).

vicentemaldonado profile image
Vicente Maldonado

First time I seen that one too. It would be interestingto see how it behaves in other languages that support increment operators.

arjayosma profile image

It really differs with the languages on how they are being evaluated by their compilers. This syntax may work with one language, and not on the other one.

I had a programming language subject before and it was in there that we were enlightened by how different languages' syntax are being evaluated. I completely agree it is interesting to see how different languages support similar syntaxes.

Great article by the way @Jeremey Grifski!

vicentemaldonado profile image
Vicente Maldonado

Yes, I would stay away from that syntax altogether. Surprises are not a good thing in programming :-)

renegadecoder94 profile image
Jeremy Grifski Author

Agreed! When I was digging into this problem, I read that the functionality is basically undefined in C/C++, totally compiler dependent. It would fun to see how other languages handle it.