Programmers write methods, also known as functions, to automate tasks that may need to be performed many times. To take advantage of this pre-written code, there are several things that we need to know:
The name of the method
What information, if any, does the method need sent into it(parameters)?
What information, if any, does the method return?
These three items together make up what is known as a method's signature. Notice, that as users of the method, we need not understand how it accomplishes its task. This concept is called abstraction. Thus, if a programmer finds a more efficient way to perform a task, they can re-write the method and not effect any calls to the method as long as they do not alter the method's signature.
Another important consideration when calling a method is to know where the method is. Here are some options:
Methods in the same class can be called using just the method name name
myMethod();
Member methods of other classes must be called from an instance of that class
str.length();
Static methods of other classes(library functions), must be called from the class name
Math.sqrt(5);
Method Headers
The method header of a Java method is the declaration of a method and has several parts:
access type - which users are allowed to call the method. The access type is public, private or protected. Public methods are accessible by all users. Private methods are accessible only by users in the class. Protected methods are accessible by users in the class and any subclasses.
operator type - does the method operate on the private instance variables of an object or not. The operator type is static if the method does not operate on the variables of an object. Otherwise, it is just left blank.
return type - the type of information that the method returns. The return type is the type of data that the method will return to the caller. Return types can be int, String, double, etc. Methods that don't return information are labeled void.
method name - the name of the method. The method name is an identifier of the method. It follows all the rules for naming variables and should describe what the method does.
parameter list - the types and number of variables that the method expects to receive. The parameter list is the list, including types, of the variables being sent into the method.
A typical method header in Java may looks like this:
public static void showAge(int age){
This method is accessible by all users (public), does not use the private variables of a class (static), does not return any information (void), is called showAge and expects an int to be sent in.
Writing Basic Methods
To start, we will be writing simple methods to accomplish tasks. At this point in time, all of our methods will start with public static. Additionally, these basic methods will not take any parameters and will not return any information.
Inside the {...} of the method is the method body. Any valid Java code can be written in the body, including input, output, calculations, conditions, method calls and loops.
Methods are also our first code that will be written outside of the main. You CANNOT write a method header and body inside the main method. Some programmers like to have their methods first (prior to the main), others like to have them after the main. I will write mine after, but you can choose where you prefer.
Let's start by creating a method that will generate and add two random numbers between 1 and 6, generating the result of a roll of two dice. The method will be public static, as all of our methods at this point will be, it will not return any information (void) and it will not take any parameters. A simple, descriptive name should be chosen - roll2Dice (notice the camel-casing and similarity to variable names). Here is what our method will look like:
public class BasicMethodLecture{
public static void main(String [] args){
//main method code
}
public static void roll2Dice(){
int die1=Integer.parseInt(Math.random()*6+1);
int die2=Integer.parseInt(Math.random()*6+1);
int total=die1+die2;
System.out.print("The player rolled: "+total);
}
}
At this point, our method isn't acting because it hasn't been called. The only method that runs automatically is the main method.
Calling Methods
To call a method that is written in the same class, we simply write the method name, followed by empty parenthesis (there are more involved processes for methods that take or return information). So, to call the method we wrote previously, we would write:
roll2Dice();
in the main method.
When calling a method from another class in the same project, we can use the class name followed by the method name. This allows us to create a library of commonly used methods and call them at will. Here is an example:
public class GameLibrary{
public static void roll1Die(){
int num=Integer.parseInt(Math.random()*6+1);
System.out.println("The player rolled: "+num);
}
public static void roll2Dice(){
int die1=Integer.parseInt(Math.random()*6+1);
int die2=Integer.parseInt(Math.random()*6+1);
int total=die1+die2;
System.out.print("The player rolled: "+total);
}
}
public class Game{
public static void main(String [] args){
System.out.println("Roll 1 Die:");
GameLibrary.roll1Die();
System.out.println("Roll 2 Dice:");
GameLibrary.roll2Dice();
}
}
In lines 2 and 6 of the GameLibrary class, we define two methods: roll1Die() and roll2Dice(). These methods take no parameters and return no information.
These methods are called from a different class in lines 4 and 6 of the Game class. The methods can be useful in a variety of different classes.
Parameters
When passing information from the main into a method, we have to use parameters. The parameters must be in the same order as the methods signature. The parameter list in the method signatures is the types and number of variables that the method expects to receive.
Variables declared in a method are local to that method. In other words, they have no value oustide of the method. So, if we declare some variables in a method (e.g. the main() method), and want to use their values in another method, we send them into the other method as parameters.
Say we have taken user input on the coordinates of two points in our main method as int x1, y1, x2, y2. The input assigns them a value. If we want to write a method that will find the midpoint of these two points, we need to send the values of the point in. So, in our main we see:
int x1, y1, x2, y1;
x1=//code for input
y1=//code for input
x2=//code for input
y2=//code for input
showMidpoint(x1, y1, x2, y2);
}//end main method
In the call to showMidpoint, x1, y1, x2, and y2 are what we call the actual parameters. In other words, these are the original values that we wanted to work with.
When we declare the showMidpoint method, we need to prepare it to receive information. We do this by declaring local method variables, called formal parameters, in the parenthesis of the method signature. The signature will look like this:
public static void showMidpoint(int a1, int b1, int a2, int b2)
a1 will take on a copy of the value of x1.
b1 will take on a copy of the value of y1, and so on.
Because they are taking on copies of the values, altering the formal parameters will have no effect on the actual parameters.
So, our finished method looks like this:
public static void showMidpoint(int a1, int b1, int a2, int b2)
{
int midX = (a1+a2)/2;
int midY = (b1+b2)/2;
System.out.println("The midpoint of the points is: ("+midX+", "+midY")";
}
Finally, what if we wanted to do these calculations with double values, instead of int values? We can overload the method. In other words, use the exact same signature with the exception of the type and/or number of parameters.
The computer will differentiate as to which version of showMidpoint to call based on the data types that are sent in.
Returns
Previously, we learned how to send information from one method into another using parameters. This is necessary because variables only exist within the method in which they are created. When we want to send a result back to the calling method, we must use a return. When a method returns information, that data needs to either be output or stored in a variable.
It is important to note the return type in the method signature. The return type is the type of information that the method returns. The return type is the type of data that the method will return to the caller. Return types can be int, String, double, etc. Methods that don't return information are labeled void.
Since the variables in a method are local to the method, altering information will not have any affect on data in the calling method. So, to be able to send information into a method and view the result of any computations/calculations in the caller, we need to return the data to the main.
Data is returned from a method using the keyword return. A method can only return one value per call. The type of information that the method is returning is specified in the signature. If a method is not going to return any data, the return type void is used.
Returning information is independent of parameters. In other words, methods can return information regardless of whether or not it takes information in.
public static int getAge()
{
int myAge=16;
return myAge;
}
Finally, when a method that returns information is called, it is important that the information that is returned is stored in a variable of the appropriate type or placed inside of an output statement for display.