5

Consider this simple code:

 // E1 
  public void doTest(String pattern) {
    int counter = 0;

    while (counter < 3) {
        counter = counter++;
    }
    System.out.println("Done");
}

This causes an infinite loop.

However if the statement that increments the counter is written like this:

E2.  counter = ++counter;

or this

E3.    counter++;

It terminates normally. I understand that the incrementing occurs after the assignment in the version that fails which explains why E2 works, but I thought java assigned the results of an increment in the variable that is incremented as in E3. So I'm perplexed as to why E1 fails but E3 does not.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Elliott
  • 5,523
  • 10
  • 48
  • 87
  • Do you know how to use a dubugger? This is a great tool which can help you understand how code like this works. – Code-Apprentice Jun 20 '13 at 21:07
  • http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop?rq=1 – fastcodejava Aug 15 '13 at 23:23
  • possible duplicate of [Is there a difference between x++ and ++x in java?](http://stackoverflow.com/questions/1094872/is-there-a-difference-between-x-and-x-in-java) – nawfal Jul 20 '14 at 09:14

4 Answers4

17
counter = counter++;

The above code has no effect on counter. It is effectively same as:

int temp = counter;
counter++;
counter = temp;

So, the value of counter is not changing at all.

On the other hand, if you use:

counter = ++counter;

The counter is incremented first, and then is re-assigned to counter. Essentially, you can simply ignore the assignment part, and keep it simply this:

counter++; // Or ++counter
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • @Elliott, you can further understand this by reading up on post and pre increments here: http://en.wikipedia.org/wiki/Increment_and_decrement_operators –  Jun 20 '13 at 21:09
2

The problem is that the value of counter at the end of the loop body is the same as it was at the beginning. The statement counter = counter++ is equivalent to:

int temp = counter;
counter = counter + 1;
counter = temp;

The postIncrement++ operator returns the value before the increment; the ++preIncrement operator returns the incremented value.

Mike Strobel
  • 25,075
  • 57
  • 69
1

Replace

 counter = counter++;

by: 1)

counter+=1;

or

2)

counter++;

Cheers!

Abhishek
  • 874
  • 2
  • 8
  • 23
0

It is better to avoid this kind assignment. The ++ is intended to be used by itself. If you want to increment by yourself you could have done counter += 1.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186