Cautious Java recursive invocation

Source: Internet
Author: User
In the Java language, when using recursive calls, if too many calls are easily caused Java.lang.StackOverflowError is stack Overflow and program execution is too slow。 This is a potential bug and affects program execution efficiency issues that need to be used with caution.
Let's see. causing java.lang.StackOverflowError-Stack OverflowProblem: [Java]  View plain  copy public class recursiontest   {           public static void recursion (int totaltimes,int time)         {           if (totaltimes > 1)            {                system.out.println ("This is the first    +  time + " call.) ");               totalTimes--;                time++;                recursion (totaltimes, time);           }            else &nbsp         {                SYSTEM.OUT.PRINTLN ("Call over,"  + time +  ");                return;            }       }              public static void main (String[] args)         {           int totalTimes =  1000000;           int time = 1;           long starttime = system.currenttimemillis ();            system.out.println ("Nesting Call start time:"  +  StartTime);  &nBsp         recursion (totaltimes, time);            system.out.println ("Nesting Call End time:"  + system.currenttimemillis ());            system.out.println ("Total time consuming:"  +  ( System.currenttimemillis ()  - starttime);            system.out.println ("------------------------------------------------------------");        }     }   modifies "totaltimes", when a certain value is reached, the following error is reported:
When developing, be careful to avoid this problem, especially if recursion is too much called, it is better to replace it with a for or whlie. The following cycle () method: [Java]View plain copy public static void cycle (int totaltimes, int time) {if (Totaltimes > 1) {Syst Em.out.println ("This is the first + time +" call.)       ");       else {System.out.println ("call ended," + Time + "Times"); Instead of the Recuresion () method: [Java]View Plain Copy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.