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!");
}
}
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 tomain, 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.voidmeans 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
printMenuorshowScore.
The order of the methods in the class doesn't matter: Java always starts at main.