Codiqo

Learn Java · lesson 22 of 61 · about 7 minutes

Defining Methods

Say goodbye to the customer between two dividers: package a line of code into your own static method and call it from main.

What you'll learn

  • Define a static method
  • Call it from main
  • Use void for methods that return nothing

A divider for the goodbye

The desk's output is getting long, so the goodbye should stand out, with a divider line above and below it. The same System.out.println twice would work, but if the divider ever changes it has to be changed twice. A method gives that line a name, printDivider, and every call prints it.

Name a piece of code

A method is a named block of code inside a class. For now, write them as static so main can call them directly:

static void cheer() { System.out.println("Go!"); }

void means the method doesn't give back a value. Calling cheer(); runs its body. Unlike C, Java doesn't care whether the method is written above or below main.

Define once, call twice

public class Main {
    public static void main(String[] args) {
        cheer();
        System.out.println("...");
        cheer();
    }

    static void cheer() {
        System.out.println("Go Phoebe!");
    }
}

Output

Go Phoebe!
...
Go Phoebe!

Why bother?

  • Reuse: write it once, call it many times
  • Names: printMenu() explains itself
  • Fix once: a bug fixed in the method is fixed everywhere it's used

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.