Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Bootcamps Get Certified Upgrade Teachers Spaces Bootcamps
   ❮     
     ❯   

Java Tutorial

Java HOMEJava IntroJava Get StartedJava SyntaxJava OutputJava CommentsJava VariablesJava Data TypesJava Type CastingJava OperatorsJava StringsJava MathJava BooleansJava If...ElseJava SwitchJava While LoopJava For LoopJava Break/ContinueJava Arrays

Java Methods

Java MethodsJava Method ChallengeJava Method ParametersJava Method OverloadingJava ScopeJava Recursion

Java Classes

Java OOPJava Classes/ObjectsJava Class AttributesJava Class MethodsJava Class ChallengeJava ConstructorsJava this KeywordJava ModifiersJava EncapsulationJava Packages / APIJava InheritanceJava PolymorphismJava super KeywordJava Inner ClassesJava AbstractionJava InterfaceJava AnonymousJava EnumJava User InputJava Date

Java Errors

Java ErrorsJava DebuggingJava ExceptionsJava Multiple ExceptionsJava try-with-resources

Java File Handling

Java FilesJava Create FilesJava Write FilesJava Read FilesJava Delete Files

Java I/O Streams

Java I/O StreamsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriter

Java Data Structures

Java Data StructuresJava CollectionsJava ListJava ArrayListJava LinkedListJava List SortingJava SetJava HashSetJava TreeSetJava LinkedHashSetJava MapJava HashMapJava TreeMapJava LinkedHashMapJava IteratorJava Algorithms

Java Advanced

Java Wrapper ClassesJava GenericsJava AnnotationsJava RegExJava ThreadsJava LambdaJava Advanced Sorting

Java Projects

Java Projects

Java How To's

Java How Tos

Java Reference

Java ReferenceJava KeywordsJava String MethodsJava Math MethodsJava Output MethodsJava Arrays MethodsJava ArrayList MethodsJava LinkedList MethodsJava HashMap MethodsJava Scanner MethodsJava File MethodsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriterJava Iterator MethodsJava Collections MethodsJava System MethodsJava Errors & Exceptions

Java Examples

Java ExamplesJava VideosJava CompilerJava ExercisesJava QuizJava Code ChallengesJava ServerJava SyllabusJava Study PlanJava Interview Q&AJava Certificate


JavaRecursion


Java Recursion

Recursion is the technique of making a function call itself. This technique provides a wayto break complicated problems down into simpler problems which are easier to solve.

Recursion may be a bit difficult to understand. Thebest way to figure out how it works is to experiment with it.


Recursion Example

Adding two numbers together is easy to do, but adding a range of numbers is morecomplicated. In the following example, recursion is used to add a range of numberstogether by breaking it down into the simple task of adding two numbers:

Example

Use recursion to add all numbers from 1 to 10.

public class Main {  public static int sum(int k) {    if (k > 0) {      return k + sum(k - 1);    } else {      return 0;    }  }  public static void main(String[] args) {    int result = sum(10);    System.out.println(result);  }}

Try it Yourself »

Example Explained

When thesum() method is called, it adds parameterk to the sum of all numbers smallerthank and returns the result. Whenk becomes 0, the method just returns 0. Whenrunning, the program follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the method does not call itself whenk is 0, the program stops there and returns theresult.



Halting Condition

Just as loops can run into the problem of infinite looping, recursive methods can run intothe problem of infinite recursion. Infinite recursion is when the method never stops callingitself. Every recursive method should have a halting condition, which is the conditionwhere the method stops calling itself. In the previous example, the halting condition iswhen the parameterk becomes 0.

It is helpful to see a variety of different examples to better understand the concept. In thisexample, the method adds a range of numbers between a start and an end. The haltingcondition for this recursive method is whenend is not greater thanstart:

Example

Use recursion to add all numbers from 5 to 10 (5+6+7+8+9+10):

public class Main {  public static int sum(int start, int end) {    if (end > start) {      return end + sum(start, end - 1);    } else {      return end;    }  }  public static void main(String[] args) {    int result = sum(5, 10);    System.out.println(result);  }}

Try it Yourself »

Be careful with recursion: it's easy to accidentally write a method that never stops or uses too much memory. But when written correctly, recursion can be both efficient and elegant.


Countdown with Recursion

This example demonstrates how to use recursion to create a countdown function:

Example

public class Main {  static void countdown(int n) {    if (n > 0) {      System.out.print(n + " ");      countdown(n - 1);    }  }  public static void main(String[] args) {    countdown(5);  }}
Try it Yourself »

The method calls itself withn - 1 untiln becomes0.


Calculate Factorial with Recursion

This example uses a recursive method to calculate the factorial of 5:

public class Main {  static int factorial(int n) {    if (n > 1) {      return n * factorial(n - 1);    } else {      return 1;    }  }  public static void main(String[] args) {    System.out.println("Factorial of 5 is " + factorial(5));  }}
Try it Yourself »

Factorial means multiplying a number by every number below it, down to 1. For example, the factorial of 5 is: 5 * 4 * 3 * 2 * 1 = 120. By definition,0! is also 1.





×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.

-->
[8]ページ先頭

©2009-2026 Movatter.jp