Java statements are grouped together into units called methods. Each method must be inside a class. It has a name, which starts with a lowercase character and typically is a verb because it does something.
When you go to a method, the term is call. When the group of statements in the method is finished, the method returns to the where it was called from.
This tutorial starts with static (also called class) methods because all applications start with the static method main. Altho main is static, as you progress in Java, you will find that relatively few of your methods will be static - only those that are self-contained, depending only on parameters. This self-contained nature makes them a good place to start the discussion of methods.
You can always identify a method call because it it followed by left and right parentheses, which may contain arguments (parameters). If you see a left parenthesis with a name preceding it, it will be a method call, or a constructor, which is very similar. Here is an example where the method names are hilited.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// File : intro-dialog/KmToMiles.java
// Purpose: Convert kilometers to miles. Use JOptionPane for input / output.
// Author : Michael Maus
// Date : 16 Apr 2005
import javax.swing.*;
public class KmToMiles {
//================================================================= main
public static void main(String[] args) {
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.
//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);
//... Computation
mi = km * 0.621; // There are 0.621 miles in a kilometer.
//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is "
+ mi + " miles.");
}
}
|
The above code defines the main method, which someone
(eg, the operating system) will call.
To do its work, main calls on other methods:
showInputDialog which is defined in the JOptionPane class),
parseDouble which is defined in the Double class, and
showMessageDialog which is also in the JOptionPane class.
When you call a static method in someone else's class, you have to precede it with the name of the class containing its definition, followed by a dot.
The calls for static and instance methods look the same, except that a static method name is preceded by the class name (unless it's in the same class when the class name can be omitted). Instance method calls are preceded by a value instead of a class name.
You could think of methods as being similat to departments /sections / groups in an organization, which are responisible for doing one thing.
When you call a method, you can pass information for it to use. These arguments (also called actual parameters) are inside parentheses following the method name. Use commas to separate the arguments if there is more than one. The previous program is shown below, but the arguments in the calls (not the main definition) are hilited.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// File : intro-dialog/KmToMiles.java
// Purpose: Convert kilometers to miles. Use JOptionPane for input / output.
// Author : Michael Maus
// Date : 16 Apr 2005
import javax.swing.*;
public class KmToMiles {
//================================================================= main
public static void main(String[] args) {
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.
//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);
//... Computation
mi = km * 0.621; // There are 0.621 miles in a kilometer.
//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is "
+ mi + " miles.");
}
}
|
The previous program is rewritten below to define a method to convert from kilometers to miles.
The method call, and the first line of the method definition are hilited.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// File : intro-dialog/KmToMilesMethod.java
// Purpose: Convert kilometers to miles using a method. JOptionPane IO.
// Author : Michael Maus
// Date : 28 Oct 2004
import javax.swing.*;
public class KmToMilesMethod {
//================================================================= main
public static void main(String[] args) {
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.
//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);
//... Computation
mi = convertKmToMi(km);
//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is "
+ mi + " miles.");
}
//========================================================= convertKmToMi
private static double convertKmToMi(double kilometers) {
// Assume there are 0.621 miles in a kilometer.
double miles = kilometers * 0.621;
return miles;
}
}
|
A call is the process of suspending one method (the caller) in the middle in order to start another method (the called method). When the called method is finished, it returns to the point immediately after the call took place. Commonly this is described as the returning to the place of the call, but of course it is really the next instruction or we would have a loop.
Terminology regarding method parameters/arguments is inconsistent, but the most common practice is the following.
Argument is the name for each of the comma-separated values in a method call. However, these are sometimes referred to as actual parameters or simply parameters. The preferred usage is argument.
Parameter is the name for each of "variable" in the method definition that corresponds to the argument in the call. The term formal parameter is sometimes used.
We'll take a look at how the convertKmToMi method is called,
because it illustrates how all methods are called. Later, when we look
at instance methods, the only difference will be the automatic addition
of one extra parameter.
Assume we've gotten to the call on line 22.
mi = convertKmToMi(km);
Before the assignment can be made, the right-hand-side must be evaluated. In this case, the method must be called. The following describes the steps in calling a method.
The only argument in this call, kilometers, is a simple
variable that doesn't require evaluation. When an expression is used
as an argument (eg, in line 25), the expression must be evaluated before
the call can be made.
When a method is called, memory is required to store the following information.
In the convertKmToMi method's stack frame there
would be space for the parameter kilometers and
the local variable miles.
The main method's stack frame has the one parameter
args and three local variables,
kmStr, km, and mi.
When the arguments are evaluated, they are assigned to the
local parameters in the called method. In the example
above, the value in km in main is assigned to
the parameter kilometers in convertKmToMi.
After the stack frame has been initialized, execution starts with the first statement and continues as normal.
When a return statement is encountered, or the end of a void method is reached, the method returns. For non-void methods, the return value is passed back to the calling method. The stack frame storage for the called method is made available for reuse by other methods. Execution is continued in the called method immediately after where the call took place.
The previous program is rewritten below to define a method to convert from kilometers to miles.
The method call, and the first line of the method definition are hilited.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// File : intro-dialog/KmToMilesMethod.java
// Purpose: Convert kilometers to miles using a method. JOptionPane IO.
// Author : Michael Maus
// Date : 28 Oct 2004
import javax.swing.*;
public class KmToMilesMethod {
//================================================================= main
public static void main(String[] args) {
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.
//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);
//... Computation
mi = convertKmToMi(km);
//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is "
+ mi + " miles.");
}
//========================================================= convertKmToMi
private static double convertKmToMi(double kilometers) {
// Assume there are 0.621 miles in a kilometer.
double miles = kilometers * 0.621;
return miles;
}
}
|
convertKmToMi methodThere are several parts to a method
public, private, or package
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}
When you define a method, you should think about who can use it. To achieve the best encapsulation (information hiding) you should always declare methods with the least visibility that works. Here are the four options, from least visible to most visible.
private - If you don't want any other class to use it,
declare it private. This is a good choice.protected - Don't use this controversial option which limits
visibility to child classes.public - Let's anyone see it. Choose this if you've defined
a method that will be used by others outside of your project.
Note that main must be
declared public so the run-time system
can call it.
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}
A method that doesn't use variables other than parameters should be declared
static. If the static keyword is omitted, the
method will be an instance method. This example uses static,
but if it's in a class that represents an object, you will usually define instance methods.
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}
Method names should begin with a lowercase letter. Method names are typically verbs, whereas variable names are usually nouns.
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}
In parentheses following the method name are the parameters (sometimes called formal parameters). There is only
one parameter in this example - kilometers.
The type of each parameter must be specified before the name (eg, double).
The parameters are variables that only exist inside the method, and they are
assigned values from the arguments (actual parameters) when the method is called.
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}
The body of a method is the statements which are executed when the method is called
are enclosed in braces following the the method header.
Additional local variables may be defined (eg, miles).
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621;
return miles;
}
A method returns to the caller after it has done what it wants.
If the method returns a value (not a void method), it must contain
a return statement that specifies a value to return.
This example returns the value in miles.
The return statement can be followed by an expression of the appropriate type, not just
a single value. For example, this method body could be replaced
by a single return statement.
private static double convertKmToMi(double kilometers) {
return kilometers * 0.621;
}
Here is another variation of the program, this time using three methods. Altho there is no real need for these methods in such a small program, large programs are in fact composed of many small methods. It is the essential way that all code is structured.
There are a couple of things worth noting in this example. Each of the user-defined method names is hilited.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
// File : simple-dialog/KmToMilesMethods.java
// Purpose; Converts kilometers to miles using two methods.
// Author : Michael Maus
// Date : 24 Apr 2005
import javax.swing.*;
public class KmToMilesMethods {
//============================================================== main
public static void main(String[] args) {
double kilometers = getDouble("Enter number of kilometers.");
double miles = convertKmToMi(kilometers);
displayString(kilometers + " kilometers is " + miles + " miles.");
}
//===================================================== convertKmToMi
// Conversion method - kilometers to miles.
private static double convertKmToMi(double kilometers) {
double miles = kilometers * 0.621; // 0.621 miles/kilometer
return miles;
}
//========================================================= getDouble
// I/O convenience method to read a double value.
private static double getDouble(String prompt) {
String tempStr;
tempStr = JOptionPane.showInputDialog(null, prompt);
return Double.parseDouble(tempStr);
}
//===================================================== displayString
// I/O convenience method to display a string in dialog box.
private static void displayString(String output) {
JOptionPane.showMessageDialog(null, output);
}
}
|