• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Bear Bibeault
  • Liutauras Vilda
  • Devaka Cooray
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Weird Loop Behaviour

 
Ranch Hand
Posts: 128
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this program which is supposed to be stuck in an infinite loop at line 12. But it doesn't, instead it prints 5. It only behaves correctly (i.e runs infinitely) when I run it in debug mode.
It never gets in the first loop starting at line 6, which is the intention.  Am I missing something?

 
Sheriff
Posts: 6801
182
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think what is happening is that number is overflowing at line 12.  It becomes negative, then the do/while runs until number is 5.
 
Master Rancher
Posts: 3437
35
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Joseph Mokenela wrote:It only behaves correctly (i.e runs infinitely) when I run it in debug mode.



That's very unlikely - it's not infinite.  In this case, it just loops very many times, which seems infinite to you when you go through the debugger.  But the computer can go through all those loops much more quickly, when you're not slowing it down to debug.  The number is actually changing a little bit each time... you have to think about, when might it eventually leave each loop, and why?

I suggest analyzing smaller parts of the problem first, to work your way up in understanding.  Can you figure out what this code will do, and why?

Then, can you figure out what this will do, and why?    

After you understand those, try looking again at the original code.
 
Marshal
Posts: 7474
509
Mac OS X VI Editor BSD Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@OP

If got hooked on this, you could also read a bit about: https://en.wikipedia.org/wiki/Two%27s_complement.
And maybe here: https://en.wikipedia.org/wiki/2,147,483,647

Also run this program:

It may won't become apparanet right away, but I expect you might revisit this after some time.
 
Grow a forest with seedballs and this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!