Java Methods
A method is a named block of code that runs when it is called. A method is defined once and can be called many times.
Define a method and call it
The sayHello method holds one print line. Main calls the method once, and that line runs.
public class Main {
static void sayHello() {
System.out.println("Hello");
}
public static void main(String[] args) {
sayHello();
}
}A call runs between other lines
Main prints its own first line, then calls the method. The method line prints before the last line of main.
public class Main {
static void printMiddle() {
System.out.println("Middle");
}
public static void main(String[] args) {
System.out.println("Start");
printMiddle();
System.out.println("End");
}
}Call a method twice
One definition serves both calls here. Each call runs the same block again.
public class Main {
static void sayHello() {
System.out.println("Hello");
}
public static void main(String[] args) {
sayHello();
sayHello();
}
}Example
public class Main {
static void printReady() {
System.out.println("Ready");
System.out.println("Set");
}
public static void main(String[] args) {
printReady();
printReady();
}
}Key points
- A method definition gives the method a name and a block.
- A call writes the method name followed by parentheses.
- The word void in a header means the method hands no value back.
- Course methods are written static for now, because main is static and calls them directly.
- A later lesson gives the static keyword its full pass.
In this example, printReady is defined once with two print lines. Main calls the method twice. Each call prints both lines again. The four printed lines come from the one definition.
Note
A method runs only when it is called, so a definition alone prints nothing.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
How is a method called?