Sub topic 1
Declare and Call a Method
A method is a named set of instructions in a Java program. You write the instructions once, then ask Java to run them whenever you need them. Asking Java to run a method is called a method call.
Methods help you organize a program. Instead of repeating the same instructions in several places, you can put them in a method and call it more than once. A useful name also tells the reader what those instructions are meant to do.
In this chapter, you will declare a method, call it, and trace the order in which its instructions run.
What you need
You need a Java Development Kit, or JDK. A JDK is a set of tools for building and running Java programs. You also need a way to save a plain text file and a terminal, which is a window where you can type commands.
You should already be familiar with basic Java syntax and classes. A class is a container for code in a Java program.
Write and run a method
Save this program in a file named MethodDemo.java:
public class MethodDemo {
static void showWelcome() {
System.out.println("Welcome!");
System.out.println("Let's learn Java methods.");
}
public static void main(String[] args) {
System.out.println("Program starts.");
showWelcome();
showWelcome();
System.out.println("Program ends.");
}
}Open a terminal in the folder containing the file. Then run:
javac MethodDemo.java
java MethodDemoThe first command uses the Java compiler to turn your written program into a form Java can run. The second command starts the program. Use the class name MethodDemo with java, without the .java ending.
You should see:
Program starts.
Welcome!
Let's learn Java methods.
Welcome!
Let's learn Java methods.
Program ends.The welcome lines appear twice, even though they are written only once in showWelcome. The program calls that method twice.
Read the declaration
A method declaration tells Java the method's name and contains the instructions for the method. In the example, showWelcome is declared inside the MethodDemo class.
The line static void showWelcome() starts the declaration:
showWelcomeis the method's name.staticmeans the method belongs to the class. This lets the example call it directly frommain.voidmeans the method does not send a result value back to its caller.()holds a place for information the method might need. Here it is empty.- The curly braces,
{and}, surround the method's body. The body is the set of instructions the method runs.
The two lines inside the body use System.out.println, a Java method that prints text on a line. The text inside double quotes is the text to print.
Indentation is the space at the start of a line. It makes the code easier to read by showing which lines are inside each pair of braces. Java relies on the braces, not the spaces, to tell where the body begins and ends.
Find the calls
A declaration and a call have different jobs. The declaration defines what showWelcome does. Each line showWelcome(); calls it.
The call uses the method name followed by parentheses and a semicolon. The parentheses are empty because this method does not need any information in its parentheses. The semicolon marks the end of the call as an instruction.
The names must match, including capital letters. Java treats showWelcome and showwelcome as different names.
Follow the order of execution
Execution is the process of running a program's instructions. When you run this program, Java calls main to begin the work shown here.
The line public static void main(String[] args) is a standard starting pattern for a Java program. The word public makes this starting method available to Java. The part String[] args is a place for text that can be supplied when the program starts. You do not need to change that line for this example.
Now trace the program:
mainprintsProgram starts.maincallsshowWelcome.showWelcomeprints its two lines. When it reaches its closing brace, Java goes back to the point after the call.maincallsshowWelcomeagain.showWelcomeprints the same two lines again. Java goes back tomain.mainprintsProgram ends.
Notice that showWelcome is written above main, but its lines do not run first. What matters here is where the calls occur. The order of the calls determines when the method runs.
Call a method from another method
A call does not have to be in main. One method can call another. Save this separate program as RoutineDemo.java:
public class RoutineDemo {
static void showRule() {
System.out.println("Wash your hands.");
}
static void getReady() {
System.out.println("Before cooking:");
showRule();
System.out.println("Gather your tools.");
}
public static void main(String[] args) {
getReady();
System.out.println("Ready to cook.");
}
}Compile and run it:
javac RoutineDemo.java
java RoutineDemoThe output is:
Before cooking:
Wash your hands.
Gather your tools.
Ready to cook.First, main calls getReady. While getReady is running, it calls showRule. After showRule finishes, Java continues with the next line in getReady. Only after getReady finishes does Java continue with the next line in main.
This pattern lets a larger task use smaller named tasks. The method name getReady describes the larger task, while showRule describes one part of it.
Avoid common mistakes
When a program does not work as expected, check these points:
- The file name must match the public class name. Save
MethodDemoinMethodDemo.java, with the same capital letters. - The call needs parentheses. Writing only the method name is not a method call. Use
showWelcome();. - The call needs a semicolon. In this example, each method call is an instruction and ends with
;. - Keep declarations inside the class, but outside other methods. The braces show where each method ends. Do not put the declaration of
showWelcomeinside the body ofmain. - Call the method where you want its work to happen. Moving a call changes when its instructions run. Removing both calls means the welcome lines will not print.
- Read the first compiler message. A compiler message is feedback from
javacabout a problem in the written program. Check the named line and the lines just above it for missing braces, parentheses, or semicolons.
Choose method names that describe the work, such as showWelcome or getReady. This makes calls easier to understand when you read the program later.
Practice
Exercise
In MethodDemo, which part defines the welcome instructions, and which part makes them run?
Show answer
The declaration of showWelcome defines them. Each showWelcome(); call makes them run once.
Exercise
In RoutineDemo, which line prints immediately after "Wash your hands."? Why?
Show answer
"Gather your tools." prints next. After showRule finishes, Java continues at the next line in getReady.
Exercise
Change MethodDemo so it prints the two welcome lines three times. Run it and check the output.
Show answer
Add a third showWelcome(); call inside main, before the line that prints "Program ends." Each welcome line will then appear three times.