Skip to content
On this page

Methods

Declaring Methods:

Methods are reusable blocks of code that perform a specific task.

java
// Method definition
public static void greet(String name) {
    System.out.println("Hello, " + name + "!");
}

Parameters and Return Values:

Methods can have parameters (input) and return values (output).

java
// Method with parameters and return value
public static int add(int a, int b) {
    return a + b;
}

Method Overloading:

Java allows method overloading, where multiple methods can have the same name but different parameter lists.

java
// Method overloading
public static int add(int a, int b) {
    return a + b;
}

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