What is the difference between i++ and ++i?

Filed under: Clean code, Java, Programming, Teaching, — Tags: ++i, difference between i++ and ++i, i++ — Thomas Sundberg — 2011-08-05

During a coaching session I got a question about a loop.

Would there be any difference in the output from a loop defined as

for (int i = 0; i < 3; i++) {
    System.out.print(i + " ");
}

and a loop defined as

for (int i = 0; i < 3; ++i) {
    System.out.print(i + " ");
}

in Java?

The answer is (of course) no, the output is identical. Both loops will result in

0 1 2

So what is the difference between i++ and ++i then?

The difference is that

This behavior difference doesn't matter in a for loop. To see the difference in behaviour, we need to execute something else.

Take a look at

int i = 1;
int j = ++i;

System.out.println("i: " + i + " j: " + j);

and

int i = 1;
int j = i++;

System.out.println("i: " + i + " j: " + j);

They will produce different output.

The output from the examples above will be:

i: 2 j: 2

and

i: 2 j: 1

Which is better, ++i or i++?

Which construct should I prefer then? The answer falls back on readability. Understanding that you want to increment a variable with one and then assign it to another variable would mean that you want to execute something like

j = ++i;

which is the equivalent of

i = i + 1;
j = i;

I would prefer the latter example, it is easier for me to read and understand.

If you want to save the current value of a variable and then increment it, you could do:

j = i++;

the equivalent would be

j = i;
i = i + 1;

Here I also think that the latter solution would be the better solution. It is clearer what you mean.

There is no difference when you use ++i or i++ on a line on its own (or in a for loop as above). My normal implementation would be to use i++ and I really don't have a good reason for doing so. It feels good.

What is a better solution is of course a matter of opinion if the only difference is how it reads. But clean code is about opinions. What is easier to read and understand? To whom is it easier? The answer has to be very easy for anybody to read it. Anybody may be a very junior developer that need to understand he code and change it somehow.

Resources



(less...)

Pages

About
Events
Why

Categories

Agile
Automation
BDD
Clean code
Continuous delivery
Continuous deployment
Continuous integration
Cucumber
Culture
Design
DevOps
Executable specification
Git
Gradle
Guice
J2EE
JUnit
Java
Javascript
Kubernetes
Linux
Load testing
Maven
Mockito
New developers
Pair programming
PicoContainer
Presentation
Programming
Public speaking
Quality
React
Recruiting
Requirements
Scala
Selenium
Software craftsmanship
Software development
Spring
TDD
Teaching
Technical debt
Test automation
Tools
Web
Windows
eXtreme Programming

Authors

Thomas Sundberg
Adrian Bolboaca

Archives

Meta

rss RSS