Methods are blocks of code that only run when they are called. You can send parameters, which are pieces of data, into a method. Methods are ways to do things, and they are also called functions.
A method must be declared inside of a class. The name of the method is used to define it, followed by parentheses ( ). Java comes with some built-in methods, like System.out.println(), but you can also make your own to do things like:
public class Main {
static void myMethod() {
// code to be executed
}
}
The name of the method is myMethod().
static means that the method is part of the Main class, not an object of the Main class. In the next part of this tutorial, you'll learn more about objects and how to use them to call methods.
This method doesn't have a return value, which is what "void" means.
To call a method in Java, write the name of the method, followed by two parentheses ( ) and a semicolon; In the following example, when myMethod( ) is called, it is used to print a text (the action).
A method can also be called multiple times:
As a parameter, information can be given to a method. Inside the method, parameters work like variables. After the name of the method, the parameters are written in parentheses. You can put in as many parameters as you like; just put a comma between each one. In the next example, there is a method that takes as a parameter a String called fname. When the method is called, we pass along a first name, which is then used inside the method to print the full name:
An argument is a parameter that is passed to a method. So, fname is an example of a parameter, and Liam, Jenny, and Anja are examples of arguments.
You can have as many parameters as you like:
Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
In the examples above, the void keyword means that the method should not return a value. If you want the method to return a value, you can use a primitive data type (like int, char, etc.) instead of void and the return keyword inside the method.
This example returns the sum of a method's two parameters:
You can also store the result in a variable (recommended, as it is easier to read and maintain):
It is common to use if...else statements inside methods: