[vc_row css_animation=”” row_type=”row” use_row_as_full_screen_section=”no” type=”full_width” angled_section=”no” text_align=”left” background_image_as_pattern=”without_pattern”][vc_column][vc_column_text]
[/vc_column_text][vc_separator type=”normal” up=”1″][vc_column_text css=”.vc_custom_1582199196163{background-color: #f6f6f6 !important;}”]
In Java, methods can call themselves; this is called recursion and is an efficient and elegant way of working with methods. Recursive methods in Java facilitate and structure our work in larger programs.
[/vc_column_text][vc_empty_space height=”30px”][vc_column_text]
A recursive method in Java is a method that is defined by having references to itself; that is, the method calls itself. Using recursive methods is a common programming technique that can create a more efficient and more elegant code. Further, a recursive method always contains a base condition, also called the trivial case, which indicates the end of the recursion and which therefore does not call itself.
Recursive methods in Java,
[/vc_column_text][vc_empty_space height=”30px”][vc_column_text]
Some terms that are good to be familiar with when working with recursive methods are:
[/vc_column_text][vc_empty_space height=”30px”][vc_separator type=”normal”][vc_empty_space height=”10px”][vc_column_text]
Let´s declare a recursive method that sums all the integers between 1 and N.
private static int summa (int N) { // Support variable int sum; // Base condition if (N == 1) { sum = 1; } else { //The method calls itself -> Recursive call sum = N + summa(N - 1); } return sum; }
The code above provides the following case,
public static void main(String[] args) { // Print the sum of all integers between 1 and 4 System.out.println(summa(4)); // Print the sum of all integers between 1 and 10 System.out.println(summa(10)); // Base condition System.out.println(summa(1)); }
Resulting in,
10 55 1
Moreover, the image below is an illustration of how the method works when N = 3.[/vc_column_text][vc_empty_space height=”30px”][vc_single_image image=”20169″ img_size=”large” alignment=”center” onclick=”link_image” qode_css_animation=””][vc_empty_space height=”30px”][vc_column_text]
[/vc_column_text][vc_empty_space][/vc_column][/vc_row]