AI Hints
Home›Java Tutorial›Defining Methods, Parameters and Return Values
Java · Lesson 55 of 120

Defining Methods

Name a block of code.

⏱ 2 min read▶ Video at 1:09:07🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A method is a named block of code. You write it once, and then call it, by name, whenever you need it. You've already used many, like println.

  • A named block of code
  • Write once
  • Call it any time

Your own method

Here's a method called greet. Static void, then the name, then round brackets. The body, in curly braces, is the code it runs. Main calls greet twice, just by writing its name, and brackets. Each call jumps into the method, runs it, and comes back. Run it. The welcome prints twice, between opening and closing.

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

    public static void main(String[] args) {
        System.out.println("Opening time");
        greet();
        greet();
        System.out.println("Closing time");
    }
}
Output
Opening time
Hello!
Welcome to the shop.
Hello!
Welcome to the shop.
Closing time

Why methods

Methods stop you repeating code. They give a name to a job, so your program reads like a story. They let you fix a bug in one place. And they make big programs, out of small, simple pieces.

keyvalue
No repeatswrite it once
Readablea name for each job
One fixfixes every call
Small piecesbuild big programs

Summary

Define a method with a name and a body, then call it by name. For now, we write static before it. We'll see why, later. Next, parameters.

Key takeaways
  • static void name() { }
  • Call: name();
  • Reuse code
Next up: Parameters — give a method some input