The understanding of Java learning recursion

Source: Internet
Author: User

Java supports recursion. Recursion is the process of defining content according to itself. As far as Java programming is concerned, recursion is an attribute that allows a method to call itself. The method that calls itself is called recursion. A typical example is the calculation of factorial, where the factorial of n is the product of all integers from 1 to n.

When the method calls itself, the memory is allocated on the stack for the new local variables and parameters, and the code of the method is executed from scratch using these new variables. When each recursive call returns, the old local variables and arguments are removed from the stack and the execution control is restored to the call point inside the method. Recursive methods are called "telescope-style" methods, which can be freely scaled.

The recursive versions of many routines are slower to execute than the equivalent iteration version because of the additional burden of function calls. A large number of recursive calls to a method can cause a stack overflow. Because local variables and parameters are stored in the stack, and each new call creates a new copy of these variables, the stack may be exhausted.

The main advantage of the recursive approach is that, for some algorithms, recursion can be used to create a version that is clearer and simpler than the iteration version. It is very difficult to implement the quicksort algorithm in an iterative way, and some artificial intelligence-related algorithms are easiest to implement with recursive schemes.

When writing a recursive method, there must be an if statement somewhere that forces the method to return without performing a recursive call. If you do not do this, once the method is called, it will never be returned.

The understanding of Java learning recursion

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.