Java Methods: Create A Method
Java Methods: Create A Method
Create a Method
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 MyClass {
static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the MyClass class and not an object of the
MyClass 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 later in this chapter.
Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
Example
Inside main, call the myMethod() method:
Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
Multiple Parameters
You can have as many parameters as you like:
// Liam is 5
// Jenny is 8
// Anja is 31