 |
What is a method?
A method is a block of code located inside a class file whose purpose is to perform only one task. An example of a method would be the task of calculating the area of a rectangle when given the height and width. When creating a method in Java, you must define the name of the method, the return type (the type of data it returns - such as void (nothing), an int, or a boolean), the parameters (what the method is given in the first place), and the body of the method (the code that does the task). Almost everything in Java is organized into methods. See the example below.
Example
/* Purpose: to create a Rect class that will calculate the area and print out the width and height of a rectangle*/
public class Rect
{
public static void main(String[] args) //this is the main method
{
double x=3.0;
double y = 4.0;
double area;
print(x,y);
area=areaRect(x,y);
//the areaRect function returns the value of the area
System.out.println("The area of the rectangle is " + area + ".");
}
//method name: print
//purpose of method: to print the width and height of the rectangle
//parameters: the width and height of a rectangle
//return: this method returns nothing
public static void print(double a, double b)
{
//the following is the body of this method
System.out.println("The width is " + a + ".");
System.out.println("The height is " + b + ".");
}
//method name: areaRect
//purpose: to calculate the area of a rectangle
//parameters: the length and width of a rectangle
//return: this method returns a double value
public static double areaRect(double a, double b)
{
return (a * b);
}
}
System Output
The width is 3.0.
The height is 4.0.
The area of the rectangle is 12.0.
Methods should be specific enough to accomplish their purpose, but also general enough so that they can be used in other programs as well. For example,
the areaRect method should be able to calculate the area of ANY rectangle, given their dimensions.
Static Initialization
Methods can be static methods or instance methods. Refer to Object-Oriented Programming Tutorial.
Access Modifiers
Methods can have their access restricted in many ways. You can specify whether a method can only be used by its container class or whether it can be used by everything outside the class. There are other options as well: refer to Object-Oriented Programming Tutorial for more details.
Return Type
The return type of a method is declared in the name of the method. The different return types are the same as the different variable types, such as int, double, boolean, or arrays. Both primitive and reference types are valid return types. The return type simply means that the method will return a value of that type back to the caller (see Calling a Method below). If the method's function does not return anything back to the caller, then the return type is void, and there will be no return statement in the method (see next topic).
Return Statement
The return statement sends a value back of the previously defined type back to the function call and immediately exits the current method. Methods do not require return statements; however, this is only the case if the return type is “void”, meaning that the method will not return anything. On the other hand, methods can have one or more return statements. Try to avoid this though. It is good programming practice to have only one return statement per method. Below is an example of how to create a return statement.
Example
public static double areaRect(double a, double b)
{
return (a * b); //this line is the return statement
}
Calling a Method
Calling a method means to tell the program to execute a particular method. Methods can be called in one of two ways. The first is to call a method in a statement all by itself. The second way is to have the call as part of another statement (e.g. a print statement or assignment statement) depending on the type that it will return. Using the above program as an example, the following code snippet will demonstrate how to use the call method.
Example
public static void main(String[] args)
{
double x=3.0;
double y = 4.0;
double area;
//the following line calls the print method, it is a statement on its own print(x,y);
//the following line calls the areaRect method; the call is a part of
another assignment statement; the areaRect method returns a double value of 12.0, therefore the variable area in the main method is now
equal to 12.0.
area=areaRect(x,y);
System.out.println("The area of the rectangle is "+area+".");
}
Parameters
Parameters are values that are passed into a method (when the method is called). In the above example, the main method passes the values of x and y to the areaRect method, which allows the areaRect method to calculate the area of the rectangle. This process is called parameter passing.
In Java, all parameters are passed by value, also known as a call-by-value.
When this happens, a local copy of the variable passed is created in the method being called. Essentially this means that the value of a particular variable (not the variable itself) is passed into the method, and then assigned to a new variable accessible only in that method. Therefore, when the local variable in the method called is changed, the original variable in the main method will NOT be affected. However, the catch is that this only applies when dealing with primitive type variables (not reference types).
Another case of parameter passing is possible
when reference variables are passed through parameters. Essentially a reference variable holds the computer address (or location) of an object in its space in memory. It points to that location where the object is being stored so that it can modify the object when neccessary. Therefore, when a reference variable is passed by value, a different REFERENCE (where it points to) to the same object will be created in the method called. As a result, this new variable will be pointing to the same location in memory as the original variable, and will therefore be able to modify the original object. If an object is passed into a method, and is changed in that method, that change affects the object everywhere, both inside and outside of the method as well.
Now, you may wonder why all variables are not just created as global variables so that every method can use them, making parameters unneccessary, right? Wrong.
The reason comes from Java's divide-and-conquer strategy. Global variables are used sparingly in larger programs because if all methods can access and change a global variable, it becomes extremely difficult to keep track
of it. Once there is a bug in one method, it is very hard to find and fix. However, if variables are made local and can only be changed in certain methods, it is much easier to track where the variable changes and if there are any errors in the program (this process is called debugging). Therefore, to make programming simpler, to reduce the chance of errors, and to find problems easier, you should use parameters.
Scope Rules of Methods
There are certain rules regarding scope that methods must follow. The code within a method is only available, or accessible, to the method itself. The only way to access code within a method is to call that method directly. Also, you can't pick and choose externally what code to execute. You can only call the method and it will run the way it has been written. For example, all the variables created in the method exist only within the method itself, and cannot be modified or otherwise accessed externally to the method. Once the program exits the method, the local variables will cease to exist. Also, it is not possible to define a method within a method.
When you use a variable in Java, the program will first search the variable in the current scope (e.g. in a for loop block). If it is not found, it will then move to the outer scope, which may be the method it is currently in. If it is not found there, the program will search in the next outer scope, which may be the outer class or the entire program (e.g. global variables). Therefore, variables must always be defined in a broader scope than the context you want to use them in. For instance, if you want to use a variable throughout a method, the variable can be defined in that method, or in the class, but not in a for loop in that method.
Method Overloading
Method overloading in Java is when methods are created with the same name, but have different parameters. As for the return type and access modifier, they may or may not be the same. The two examples below have the same method name, but a different parameter list.
Example
public static void print(double a, double b)
{
System.out.println("The width is " + a + ".");
System.out.println("The height is " + b + ".");
}
public static double print(double a)
{
System.out.println("The width is " + a + ".");
return (a +1);
}
Although the second method is not very practical, it demonstrates how the method can have a different return type. If you define two methods like these ones in the same program, they will not throw errors, but will act as totally distinct methods. For example, if you call the print function with two parameters and no return, the first function will be accessed.
|
|
 |
|