• Post Reply Bookmark Topic Watch Topic
  • New Topic

why is this an infinite loop?  RSS feed

 
Zanna Bianca
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer of one question in chapter 2 of "Oracle Certified Associate Java SE 8 Programmer I Study Guide - Jenny Boyarsky and Scott Selikoff" is 'The code contains an infinite loop and does not terminate.', but I tried it in Eclipse and it terminated after 11 times printed "Hello World":/

Here the question:

9. How many times will the following code print "Hello World"?

3: for(int i = 0; i<=10;){
4: i++;
5: System.out.println("Hello World");
6: }

A. 9

B.10

C.11

D. The code will not compile because of line 3.

E. The code will not compile because of line 5.

F. The code contains an infinite loop and does not terminate.

According to the book the answer is F:

"F. In this example, the update statement of the for loop is missing, which is fine as the
statement is optional, so option D is incorrect. The expression inside the loop increments
i but then assigns i the old value. Therefore, i ends the loop with the same value"

I don't see any explanation why it should assign i the old value? Could you please help me to understand?

Thanks
 
Stephan van Hulst
Saloon Keeper
Posts: 7984
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure line 4 isn't i = i++ ?
 
Zanna Bianca
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh you're right, it is indeed i = i++;
and in this way I got an infinite loop...now I'm more confused, why with only i++; I got a terminated loop? what is the difference?
 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

It's an well-known mistake. i++ means, "Use i, then increment it." When you say i = i++, you use i (that is, the value of i before incrementing), then you increment it -- but the incremented value is lost.
 
Zanna Bianca
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for having me!:-)

Does it mean that i = i++ is never really useful?
 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is peculiar Java craziness that we had a thread about or diverted a thread to.

i = 0;
i = i++
System.out.println(i);

It will print 0!!!
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really want some fun, you definitely have to look at this thread. It's all about the quirkiness of the i = i++; statement
 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roel De Nijs wrote:If you really want some fun, you definitely have to look at this thread. It's all about the quirkiness of the i = i++; statement

You must keep some kind of index to threads. You always have the previous one or better one at hand.
 
Roel De Nijs
Sheriff
Posts: 11338
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guillermo Ishi wrote:You must keep some kind of index to threads. You always have the previous one or better one at hand.

Do you know these forums offer some functionality to bookmark (interesting) threads? If you see a topic you want to keep for future reference, just click on the "Bookmark Topic" button at the top (or bottom) of the topic.
 
Zanna Bianca
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you all very much! I think that is the best forum ever;)
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guillermo Ishi wrote:. . . that we had a thread about or diverted a thread to.
. . .
We have lots of threads about that. That behaviour is exactly in line with the stipulations of the Java® Language Specification.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We also have a FAQ on this subject: http://www.coderanch.com/how-to/java/PostIncrementOperatorAndAssignment
 
Shawn Lau
Ranch Hand
Posts: 38
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't even know why books would suggest that. Its bad programming style. Sometimes books make simple things complicated.

i++ increments the value of i after it is used
++i increments it before it is used.

i = i++ SHOULD throw a compiler error or warning, but it doesn't.

The clearest code is the best code.

i += 1 is no faster than i = i +1

i = i < 2 ? i : 10
is no faster than

if ( i < 2) i =2
else
i = 10;


The clearest code is the best code.
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shawn Lau wrote:I don't even know why books would suggest that. Its bad programming style.


I'd agree with you there, except for one thing: the book in question is one of those which trains you to pass a certification exam. And those exams are packed full of horrible code examples which are supposed to test your knowledge of Java. Those books should have a big disclaimer in the front saying not ever to write code like their examples; I don't know if they do though. And yeah, "i = i++" is something you should never ever find in real code.
 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Clapham wrote:
And those exams are packed full of horrible code examples which are supposed to test your knowledge of Java. Those books should have a big disclaimer.

Good point. I think everybody has that in the back of their mind, though. Years ago I a ran across a "why I hate Java" page chocked full of idiosyncratic examples like the above.
I don't think you would run across something like the above in ocajp7 but I can't swear to it because I was dozing off and out of my mind when I took it. The ocajp8 has a reputation for being a little trickier so it might, I took the beta version of it and I think it was trickier.
 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:that behaviour is exactly in line with the stipulations of the Java® Language Specification.

I know! But rationalize it how you will, the i++ comes before the print i, so it should print 1.
 
Stephan van Hulst
Saloon Keeper
Posts: 7984
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, and then just ignore the assignment? When I use the assignment operator, I like that it actually assigns stuff. In this case it assigns 0. The ++ operator has a much higher precedence than the assignment, and with good reason.

Rationalize it as you will, you're assigning 0, so it should print 0.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no rationalisation to it. The behaviour is very simple to understand.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few minutes ago, I wrote:. . . The behaviour is very simple to understand.
… and that is one of my bigger lies this month

Postincrement is one of those things which cause no end of confusion to beginners. Both i++ and ++i have two values. There is the value of the whole expression and there is the value of the variable i. The Java® Language Specification (=JLS) tells you everything:-
the value 1 is added to the value of the variable and the sum is stored back into the variable.
At line 2 the value of i is 124. But
The value of the postfix increment expression is the value of the variable before the new value is stored.
That means the value of the whole expression i++ is 123. This is what confuses people, that there are two different values going round. If you use the daft code
i = i++;
… all you achieve is reassigning i to its old value.

There are similar problems with i--. In the case of ++i and --i, there are also two values, that of the variable and that of the whole expression. But the value of the expression is equal to the new value of the variable, so people find that much easier to understand.

This behaviour goes back to the days of C in 1972 (and probably before that), but it is not strictly defined in C. The JLS does however define this behaviour strictly.

[edit]Note that this is one of the few places where the JLS is easier to understand than the behaviour in real life
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:This behaviour goes back to the days of C in 1972 (and probably before that), but it is not strictly defined in C.

Really? It was certainly defined that way in my Ansi C book. Do you mean that the behaviour wasn't explicitly defined in K & R?

Personally, I wish Java had never allowed the damn things (postfix operators) - although oddly, it's the way most of us (including me) code our for loops:
  for(int i = 0; i < array.length; i++) { ...

Which probably just goes to prove that if you want consistency, don't ask a programmer.

Winston
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ANSI C is much later than K&R. In the copy of K&R we have here, the behaviour is slightly different from Java®
Kernighan & Ritchie, in the C Programming Language 2/e (1988) page 46 wrote:… But the expression ++n increments n before its value is used, while n++ increments n after its value has been used. This means that in a context where the value is being used, not just the effect, ++n and n++ are different. If n is 5, then
    x = n++;
sets x to 5, but
    x = ++n;
sets x to 6. In both cases, n becomes 6. …
That copy does have ANSI C written on the cover.

It might be different from Java®, but you will never actually notice the difference. The first time I came across this problem I tried this sort of code with three different C compilers:-Two printed 4 and one 5 I was told that such behaviour is not fully defined for all C implementations.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The expressions i++ and ++i are useful because you can add to the last element of a partially filled array:-
andIn the latter case you may need to null out the array elementHave I got all the indices in the right places?
 
Shawn Lau
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally, I wish Java had never allowed the damn things (postfix operators) - although oddly, it's the way most of us (including me) code our for loops:
for(int i = 0; i < array.length; i++) { ...




I don't see a problem with the decrement operator in for loops. I think it makes the code concise. My problem is when people use stuff like :



It saves no time over the more clear



And stuff like the following is plain ridiculous:

 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Trouble is, the C chappies used to work with small screens and believed it was good practice to write the shortest code possible. I think they believed the computer would overload and burn out if you pushed the space bar more than once per page. That is the explanation for abominations like what you have just demonstrated.
 
ruthie pratap
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use format of for loop as
for(initiation,limit,increment)
{
(comments);
}
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch, ruthie!

I believe OP knows that this is a proper way to write a for loop.
The code OP posted is from a certification study guide and is made tricky on purpose.

Also, please read this → UseCodeTags (this is a link).
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have made the same mistake as you, using commas in the header of a for loop. It is for (initialisation; continuation; increment) ... with semicolons.

And welcome to the Ranch
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Trouble is, the C chappies used to work with small screens and believed it was good practice to write the shortest code possible. I think they believed the computer would overload and burn out if you pushed the space bar more than once per page. That is the explanation for abominations like what you have just demonstrated.

Not entirely true, I think. Don't forget that a lot of this stuff was in the days before optimizing compilers, and I seem to remember that the construct a[i++] could produce tighter machine code than:
  a[i];
  i++;

And while I quite agree that it generally has no business in a Java program, I do have to admit to a perverse admiration for the elegance of stuff like:Like I say: if you want consistency, don't ask a programmer - especially an old one.

Winston
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surely you can only write such code in Java® because C/C++ don't support myArray.length?
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!