Task 1 of 8 · 0 solved · 8 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

3.1 Methods — where a method lives

Lesson

A method sits next to main

Until now everything you wrote went inside main. A method is different: it is declared inside the class but outside main — as a second block, next to it. Then main calls it by name.

So a program with a method has three layers: the class on the outside, and inside it two blocks side by side — your method and main.


Worked example

public class Main {

    static void sayHi() {          // the method: declared next to main
        System.out.println("Hi!");
    }

    public static void main(String[] args) {
        sayHi();                   // main calls it
        sayHi();                   // and can call it again
    }
}

Two things to notice. The word static is what lets main call the method directly — treat it as part of the recipe for now. And a method does nothing until it is called: declaring sayHi prints nothing by itself.

The order does not matter: the method may be written above or below main, and the program behaves the same.


▶ Try it: the whole program is here — method and main together. Run it, then add a third sayHi(); call, or move the method below main and run again.



Where is a method declared?


A program declares sayHi() but never calls it. What is printed?


Why is static written in front of the method here?


True or false?


Here the method is written below main. Type exactly what this program prints.

public class Main {

    public static void main(String[] args) {
        sayHi();
    }

    static void sayHi() {
        System.out.println("Hi!");
    }
}