Java Methods
A method is a block of code which only runs 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.
Create a Method:
A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().
static void myMethod() {
// code to be executed
}
static:means that the method belongs to the Main class and not an object of the Main class.
void:means that this method does not have a return value.
Call a Method:
To call a method in Java, write the method’s name followed by two parentheses () and a semicolon ;.
public static void main(String[] args) {
myMethod();
}Parameters and Arguments:
Information can be passed to methods as parameter. Parameters act as variables inside the method.
Get Bora Fazli’s stories in your inbox
Join Medium for free to get updates from this writer.
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.
static void myMethod(String name) {
System.out.println("Name is " + name);
}
static void myMethod(String name, int age) {
System.out.println(name + " is " + age);
}Return Values:
If you want the method to return a value, you can use a primitive data type (int, char…) instead of void, and use the return keyword inside the method.
static int myMethod(int x) {
return 5 + x;
}





