Home › Java Tutorial › Java methods
Java methods
Reusable blocks of code.
A method has a return type, a name and parameters. Use void when it returns nothing. static methods belong to the class, so main can call them directly. A method can call itself: this is recursion.
Example code
public class Main {
static int add(int a, int b) {
return a + b;
}
static void greet(String name) {
System.out.println("Hi " + name);
}
static int fact(int n) {
return n <= 1 ? 1 : n * fact(n - 1);
}
public static void main(String[] args) {
greet("Ada");
System.out.println(add(2, 3));
System.out.println(fact(5));
}
}