Java chapters

Chapter 9 of 17

Functions

Try this in our Java Compiler →

Why functions?

A function is a named, reusable block of code. It takes inputs (called parameters), runs some logic, and optionally returns a value. Functions are the single most important tool for keeping a program organised — instead of one giant script, you build a library of small, well-named functions and combine them.

static int add(int a, int b) {
    return a + b;
}

public static void main(String[] args) {
    System.out.println(add(2, 3));
}

Parameters and return values

Parameters are the variables a function declares to receive its inputs. The return value is what the function hands back to whoever called it. A function with no return value is sometimes called a procedure or a void function — it works by side effect (printing, saving, sending) rather than by computing a result.

Scope and pure functions

A function with no hidden state is called "pure" — given the same inputs it always returns the same output. Pure functions are easy to test and reason about. Aim to write pure functions whenever you can, and isolate the impure parts (I/O, randomness, time) at the edges of your program.

Details for java

Checked exceptions must be caught or declared. NumberFormatException is a runtime error requiring an input policy. Catch failures you can explain instead of returning a fabricated answer.

Practice and verify

Change one meaningful value in the example and predict the result before running. Then test a boundary or empty value. Explain what changed and why, rather than only copying the output.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on