Java Arena
Step 1 of 5

Defining and calling a method

So far every program has been one long main method. As programs grow, that gets hard to read. A method is a named piece of code: you write it once and run it by its name, as often as you like.

public class Main {
    public static void main(String[] args) {
        System.out.println("Let's begin.");
        greet();
        greet();
        System.out.println("Done.");
    }

    public static void greet() {
        System.out.println("Hello from a method!");
    }
}
Output
Let's begin.
Hello from a method!
Hello from a method!
Done.
  • public static void greet() { ... } defines the method. It sits inside the class, next to main, never inside another method.
  • greet(); calls it: Java runs the method's lines, then carries on after the call.
  • Every method in these lessons starts with public static; the modules on objects explain what that means. void means the method gives nothing back. Module 11 is about methods that do.
  • Method names follow the same style as variable names: a small first letter, and a capital for each new word, such as printMenu or showScore.

The order of the methods in the class doesn't matter: Java always starts at main.

Your task

Challenge 1 of 3

Fill in the blanks, so main calls printBanner before and after the welcome. The program prints:

**********
Welcome!
**********

Challenge 2

Write a method printRules() that prints two lines, No running and then No diving. The check calls your method:

No running
No diving

Challenge 3

Write two methods: morning() prints Good morning and evening() prints Good evening. Then make main call them, so the program prints:

Good morning
Good evening
Good morning