Methods in Java: parameters, return values and recursion
Lesson 8 of 16 · Java
A method is a named part of a program that does one job – like a function in C or Python. Methods make programs shorter, prevent repeated code and make it easier to find mistakes. Here we use static methods, which are called without an object; object methods come in the lesson about classes.
Before you start: what you need to know first – loops, arrays. How to learn: type in and run each example, and try to solve the tasks at the end on your own first; open the hint and the solution only after that. All the programs are in Java (Java 17 or newer); each one has been compiled and run and gives the output shown.
Defining and calling a method
A method has a header (modifiers, the return type, the name, the parameters) and a body in curly brackets. The return statement returns the result and ends the method.
public class Main {
// static: the method belongs to the class and is called without an object
// int: the type of the value it returns; (int x): a parameter
static int square(int x) {
return x * x;
}
// void: the method does not return a value, it just does something
static void line(int length, char symbol) {
for (int i = 0; i < length; i++)
System.out.print(symbol);
System.out.println();
}
public static void main(String[] args) {
line(20, '=');
for (int i = 1; i <= 4; i++)
System.out.println(i + " squared is " + square(i));
line(20, '-');
int sum = square(3) + square(4); // the result is used in an expression
System.out.println("3^2 + 4^2 = " + sum);
}
}
Output:
====================
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
--------------------
3^2 + 4^2 = 25
When a method is called, the arguments (the actual values) are given to the parameters in order: in the call line(20, '=') the parameter length gets 20, and symbol gets '='.
Methods that answer yes/no
A method of type boolean makes a condition readable: if (isPrime(n)) reads like a sentence.
import java.util.Scanner;
public class Main {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int d = 2; (long) d * d <= n; d++)
if (n % d == 0)
return false; // return ends the method straight away
return true;
}
static int digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt(), b = sc.nextInt();
// prime numbers from the interval whose digit sum is also prime
for (int x = a; x <= b; x++)
if (isPrime(x) && isPrime(digitSum(x)))
System.out.print(x + " ");
System.out.println();
}
}
Input:10 50
Output:
11 23 29 41 43 47
Passing arguments: a copy of the value
Java always passes arguments by value: the method gets a copy. Changing a primitive parameter (int, double…) does not affect the variable used in the call. With arrays and objects the reference is copied – the method works with the same array, so changes to the elements stay visible.
import java.util.Arrays;
public class Main {
static void increase(int x) {
x = x + 10; // only the copy changes
}
static void increaseAll(int[] array) {
for (int i = 0; i < array.length; i++)
array[i] += 10; // the original array changes
}
public static void main(String[] args) {
int a = 5;
increase(a);
System.out.println("a = " + a);
int[] numbers = {1, 2, 3};
increaseAll(numbers);
System.out.println(Arrays.toString(numbers));
}
}
Output:
a = 5
[11, 12, 13]
Method overloading
Several methods can have the same name if they differ in the number or types of their parameters. Java chooses the method according to the arguments in the call:
public class Main {
static int max(int a, int b) {
return a > b ? a : b;
}
static int max(int a, int b, int c) { // same name, three parameters
return max(max(a, b), c);
}
static double max(double a, double b) { // same name, a different type
return a > b ? a : b;
}
static int max(int[] array) { // an array as a parameter
int m = array[0];
for (int x : array)
m = max(m, x);
return m;
}
public static void main(String[] args) {
System.out.println(max(3, 8));
System.out.println(max(3, 8, 5));
System.out.println(max(2.5, 1.5));
System.out.println(max(new int[]{4, 9, 1, 7}));
}
}
Output:
8
8
2.5
9
This is exactly why System.out.println works with a number, with text and with a character – there are several overloaded versions.
Recursion: a method that calls itself
A recursive method solves a problem by reducing it to a smaller problem of the same kind. It must have a base case in which it no longer calls itself, otherwise it calls itself forever (the error StackOverflowError).
public class Main {
// n! = n · (n-1)!, 0! = 1
static long factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // reducing to a smaller problem
}
// GCD(a, b) = GCD(b, a % b), GCD(a, 0) = a (Euclid's algorithm)
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
// printing a number in binary
static void binary(int n) {
if (n > 1)
binary(n / 2); // first print the higher digits
System.out.print(n % 2);
}
public static void main(String[] args) {
System.out.println("10! = " + factorial(10));
System.out.println("GCD(84, 36) = " + gcd(84, 36));
binary(37);
System.out.println();
}
}
Output:
10! = 3628800
GCD(84, 36) = 12
100101
More about recursion and about when a loop is better: Recursion.
Practice tasks
Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
TASK 01Difficulty: easy
Perfect numbers
A number is perfect if it is equal to the sum of its divisors that are smaller than itself (6 = 1 + 2 + 3). Write a method static int divisorSum(int n) and use it to print all the perfect numbers up to n, separated by spaces.
Example
Input
1000
Output
6 28 496
Hint
Look for divisors up to n / 2. In main: for every x from 2 to n check divisorSum(x) == x.
Solution (Java)
import java.util.Scanner;
public class Main {
static int divisorSum(int n) {
int sum = 0;
for (int d = 1; d <= n / 2; d++)
if (n % d == 0)
sum += d;
return sum;
}
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
StringBuilder sb = new StringBuilder();
for (int x = 2; x <= n; x++)
if (divisorSum(x) == x)
sb.append(sb.length() > 0 ? " " : "").append(x);
System.out.println(sb);
}
}
TASK 02Difficulty: medium
Fast power
Write a recursive method static long power(long a, int n) that calculates an in log n steps: if n is even, an = (an/2)2, and if it is odd, an = a · an−1. Read a and n and print the result (the result fits in a long).
Example 1
Input
2 62
Output
4611686018427387904
Example 2
Input
3 5
Output
243
Hint
Base case: n == 0 returns 1. For an even n calculate p = power(a, n / 2) once and return p * p – do not call the method twice.
Solution (Java)
import java.util.Scanner;
public class Main {
static long power(long a, int n) {
if (n == 0) return 1;
if (n % 2 == 0) {
long p = power(a, n / 2); // one call for half the power
return p * p;
}
return a * power(a, n - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
int n = sc.nextInt();
System.out.println(power(a, n));
}
}
Common mistakes and tips
A method is written outside the main method, but inside the class.
A method that is not void must return a value in every case – otherwise you get the error "missing return statement".
Variables declared in a method (local variables) are not visible in other methods; pass data through parameters and return values.
Recursion without a base case ends with the error StackOverflowError.
Check your knowledge
Open the quiz
Methods in Java
1. What does void mean in a method header?
2. A method changes the value of an int parameter. What happens to the variable used in the call?
3. When may two methods have the same name?
4. What must every recursive method have?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.