Defining and Calling Methods

What is a Method?

A method is a named block of code that runs when it is called. Methods let you write logic once and reuse it, and they split a big program into small readable pieces. (Other languages call them functions.)

static returnType methodName(parameters) {
    // body
}
PartMeaning
staticbelongs to the class, so main can call it directly (objects come later)
void / a typevoid = returns nothing; otherwise the type of the returned value
namecamelCase verb: printBill, calculateTax
parametersinputs in brackets, may be empty

Example

Example

public class Main {
    static void greet() {
        System.out.println("Hello from a method!");
    }

    static void printLine() {
        System.out.println("--------------------");
    }

    public static void main(String[] args) {
        printLine();
        greet();
        greet();      // call as many times as you like
        printLine();
    }
}

Output

--------------------
Hello from a method!
Hello from a method!
--------------------

Note: Methods are declared inside the class but outside other methods. You cannot define a method inside main.