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. Use methods to structure and reuse code.
Create a Method
A method must be declared within a class. It is defined with the return type and 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.
The following example calls a method from the main function and outputs "I just got executed!".
public class MyClass {
public void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
MyClass c = new MyClass();
c.myMethod();
}
}
Method Parameters
Information can be passed to methods as parameters. Parameters act as variables inside the 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.
The following example has a method that takes a String called name as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name:
public class MyClass {
public void myMethod(String firstName) {
System.out.println(firstName + " Refsnes");
}
public static void main(String[] args) {
MyClass c = new MyClass();
c.myMethod("Liam");
c.myMethod("Jenny");
c.myMethod("Anja");
}
}
Return Values
The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method. The following programm will add x to 5 and ouput 8:
public class MyClass {
public int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
MyClass c = new MyClass();
System.out.println(c.myMethod(3));
}
}
Source: