• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why infinite loop

 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey friend i have a problem with following code

The problem with the above code that it's going in the infinite loop why and when i am removing the code at line 2 its working fine otherwise infinite loop why?
Regard
Arun kumar maalik
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In your class create a no-arg constructor. In the constructor do a System.out.println("constructing an object"). Then run your program.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Arun Maalik:

The problem with the above code that it's going in the infinite loop why and when i am removing the code at line 2 its working fine otherwise infinite loop why?



Line 2 in the code results in creating an object of the same class for the object created in line 4.

This object in turn is forced to create another object wirthin it, and so on. This process will repeat itself leading to infinite loop.
This is similar to calling a recursive method without giving the exit condition. Thus, in the above code, you are recursively creating objects of the same class, without any condition to stop the process it goes into infinite loop.

But the execution stops at some point of time,atleast in Java 5, giving an error.

Removing line 2, removes the above cycle of events. So, the code does not
go into infinite loop.
[ March 02, 2007: Message edited by: Thulasi Prasanna ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic