Methods: Reusable Blocks of Code

What is a method?

A method is a named block of code that does one job. You write it once and call (use) it whenever you need it. main itself is a method!

Think of it like this: A method is like a recipe card for “make tea”. Instead of explaining every step each time, you just say “make tea”, and whoever reads the card does all the steps.

public class Main {
    static void greet() {
        System.out.println("Hello!");
        System.out.println("Welcome to Java.");
    }

    public static void main(String[] args) {
        greet();
        System.out.println("---");
        greet();
    }
}

Output

Hello!
Welcome to Java.
---
Hello!
Welcome to Java.
  • static void greet() creates (defines) a method called greet.
  • void means “this method doesn't give back an answer”.
  • greet(); runs (calls) it.

For now, write static before every method you put next to main. You'll learn exactly what static means in the Classes module.

Tip: Give methods verb names that say what they do: printMenu, calculateTotal, isValid.

HOME LABS COMMUNITY DASHBOARD