Funktionen und Rekursion in Java 17: Eine ausführliche Anleitung
Functions and Recursion in Java
Introduction: Why Do We Need Functions?
Imagine you are writing a program to manage a family budget. You need to add up income from different sources several times. Writing the same thing each time: int result = a + b; — is boring and inconvenient. And if you make a mistake in one place? You'll have to fix it everywhere.
Functions (or methods) are like little helpers. You write the instruction once, give it a name, and then just call it by name when needed. This makes the code shorter, clearer, and safer.
Recursion is a special technique where a function calls itself. It sounds strange, but it is very helpful for solving problems that can be broken down into similar but simpler ones (for example, reversing a string or traversing all elements of a list).
Basic Syntax of Functions in Java 17
A function in Java looks like this:
public static returnType functionName(type parameter1, type parameter2) {
// function body — instructions
return result; // if type is not void
}
Let's break it down:
- public static — for now, just remember that this is needed for the function to work. You'll learn more details later in the course.
- returnType — what the function gives back:
int(number),String(string),double(decimal). If it returns nothing, we writevoid. - functionName — come up with a clear name:
sum,max,reverse. - parameters — the data the function receives as input.
- return — the command that returns the result.
Example 1: Sum Function (Family Budget)
import java.util.Scanner;
public class Main {
// Function that adds two numbers
public static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first income: ");
int income1 = scanner.nextInt();
System.out.print("Enter second income: ");
int income2 = scanner.nextInt();
int total = sum(income1, income2);
System.out.println("Total income: " + total);
}
}
How it works: We created a function sum. In main, we read two numbers from the keyboard, pass them to the function, and it returns the sum.
Example 2: Temperature Comparison Function
import java.util.Scanner;
public class Main {
public static double findMax(double t1, double t2) {
if (t1 > t2) {
return t1;
} else {
return t2;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first temperature: ");
double temp1 = scanner.nextDouble();
System.out.print("Enter second temperature: ");
double temp2 = scanner.nextDouble();
double maxTemp = findMax(temp1, temp2);
System.out.println("Higher temperature: " + maxTemp);
}
}
Here the function returns the larger number.
Example 3: Even Number Check (Boxes at a Factory)
import java.util.Scanner;
public class Main {
public static boolean isEven(int number) {
return number % 2 == 0; // true — even, false — odd
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many boxes were produced? ");
int boxes = scanner.nextInt();
if (isEven(boxes)) {
System.out.println("The number of boxes is even, can be packed in pairs.");
} else {
System.out.println("The number is odd, needs checking.");
}
}
}
Recursion: A Function Calling Itself
Recursion is useful when a problem is similar to itself but slightly smaller. For example, reversing a string: you can take the last character and append it to the reversed string without the last character.
Example 4: String Reversal (Recursion)
import java.util.Scanner;
public class Main {
public static String reverse(String str) {
// Base case: if the string is empty or has one character — return it
if (str == null || str.length() <= 1) {
return str;
}
// Recursive case: last character + reverse(string without last character)
return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String text = scanner.nextLine();
String reversed = reverse(text);
System.out.println("Reversed string: " + reversed);
}
}
How it works: reverse("hello") → 'o' + reverse("hell") → 'o' + 'l' + reverse("hel") and so on, until the string becomes empty.
Example 5: Finding the Minimum Element in a List (Recursion)
import java.util.Scanner;
public class Main {
// Function finds the minimum in an array, starting from index
public static int findMin(int[] arr, int index) {
// Base case: if we reach the last element — that is the minimum
if (index == arr.length - 1) {
return arr[index];
}
// Find the minimum in the remaining part
int minOfRest = findMin(arr, index + 1);
// Compare the current element with the minimum from the rest
if (arr[index] < minOfRest) {
return arr[index];
} else {
return minOfRest;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);