Java Methods and Functions

Methods and functions in Java are blocks of code that perform a specific task. They provide a way to modularize code, making it easier to read, understand, and maintain.

Method Declaration

In Java, a method is declared within a class using the following syntax:


accessModifier returnType methodName(parameterList) {
    // Method body
}

Function Example

Below is an example of a simple function in Java that calculates the sum of two numbers:


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

Method Overloading

Method overloading allows a class to have multiple methods with the same name but different parameters. This is useful when you want to perform similar tasks with different types of inputs.


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

public static double sum(double a, double b) {
    return a + b;
}

Recursion

Recursion is a programming technique where a function calls itself to solve a problem. Here's an example of a recursive method to calculate the factorial of a number:


public static int factorial(int n) {
    if (n == 0) {
        return 1;
    }
    return n * factorial(n - 1);
}