Java Methods
A method is a block of code that performs a task and runs only when it is called. Methods make code reusable.
accessModifier returnType methodName(parameters) {
// body
return value;
}
Example
public class Main {
static int add(int a, int b) {
return a + b;
}
static int factorial(int n) { // recursive method
if (n <= 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println("Sum = " + add(7, 8));
System.out.println("Factorial of 5 = " + factorial(5));
}
}
Sum = 15
Factorial of 5 = 120
Method Overloading
Several methods with the same name but different parameter lists.
static int area(int s) { return s * s; }
static int area(int l, int b) { return l * b; }
System.out.println("Area of square: " + area(4));
System.out.println("Area of rectangle: " + area(4, 6));
Area of square: 16
Area of rectangle: 24
Track your progress through the Java course