A method is a block of code that runs only when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.
💡 Analogy time: Think of a method like a recipe in a cookbook.
- The recipe contains a specific set of instructions to bake a cake.
- Those instructions just sit in the book doing nothing until you actually decide to call (use) the recipe.
- Sometimes, a recipe requires ingredients like flour and sugar. In Java, these ingredients you hand to the recipe are called parameters.
Why use methods? To reuse code: define the code once, and use it many times.
A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions.
public class Main {
// This is a static method
static void myMethod() {
// The body of the method
System.out.println("I just got executed!");
}
public static void main(String[] args) {
// Method is called here
myMethod();
}
}
myMethod() is the name of the method.static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.void means that this method does not have a return value. You will learn more about return values in the next chapter.To call a method, you write the method's name followed by two parentheses () and a semicolon ;.
In the following example, myMethod() is used to print a text (the action) when it is called.
public class Main {
static void myMethod() {
System.out.println("Hello from myMethod!");
}
public static void main(String[] args) {
myMethod(); // Call the method
myMethod(); // Call it again
myMethod(); // And again
}
}
When you call a method, how does Java know where to go back to once the method finishes? It uses something called the Call Stack.
🥞 The "Stack of Plates" Analogy: Imagine a stack of plates. You can only add a plate to the top, and you can only remove a plate from the top.
- When you run your program, Java puts the
main()method plate on the empty table.- Inside
main(), you callmyMethod(). Java pausesmain(), grabs a new plate formyMethod(), and places it on top of themain()plate.- Java executes the code on the top plate (
myMethod()).- When
myMethod()is finished, Java removes its plate from the stack and throws it away.- Now, the
main()plate is back on top, so Java resumes right where it left off!If a method calls another method, which calls another method, the stack keeps growing. If it grows too large (e.g., an infinite recursion), it falls over, resulting in a famous error called a
StackOverflowError!
calculateTotal should not also save data to a file.How do you call a method named `myFunction`?