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.
Why use methods? To reuse code: define the code once, and use it many times.
​
A method must be declared within a class, but OUTSIDE of main. 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:
To Call A Method
In the following example, myMethod() is used to print a text (the action), when it is called:
​
This code will print out "I just got executed!"
Parameters and Arguments
Information can be passed to methods as parameter. 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 fname as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name:
Output:
Jordan LName
Dylan LName
Jack LName
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:
​
This example returns the sum of a method's two parameters and is stored in main under 'z':
A Method with If...Else
It is common to use if...else statements inside methods. If you do not understand what an if...else statement is, it is listed under coding as Conditions.
The example below shows a method that combines an if..else condition below. This strip of code could be used to check the of people and see if they are old enough to drink.