| In Java, methods are used to break up your programs into manageable pieces
(these pieces of code are called "modules"). |
|
The advantage to creating multiple methods over having all of your code
in a single method (the main( ) method) include ...
- Methods allow you to break down your program into smaller more manageable
segments of Java code. This process makes it less difficult to write larger
Java programs and more importantly, it makes the process of fixing
(debugging) these larger Java programs much easier.
- Methods allow you to save time by reusing code. If you are repeating a
collection of tasks over and over again using different variables but doing
the same processing, then you should capture all of this code in a method.
You can then re-use this code in various sections of your program by calling
that method. Methods are different from loops because loops may only
repeat code in one section of your Java Program, whereas methods may have
the capability to be called from almost anywhere inside your program.
|
|
|
There are two things you must do in order to use a user-defined method
in a Java program...
- Define the Method - this is done inside of a class
- Invoke the Method - this is done either in the main method or from
another method
|
| The first thing you must do is define the method, which means that you
must write all the Java instructions that make up the functionality of that
method. This is done by creating a header for the method and then
placing the instructions for the method between curly braces. You must also
determine what parameters
(also called arguments) that the function must have in order to perform its
task. Parameters are the pieces of
data that you send into the function. Most functions also send back information
(the data passed back from the function is known as the return
value of the function). |
|
| A Method definition
is the actual code of an action. |
|
|
The definition of a method consists of the function
header and its body:
access_rights
scope return_type
method_name (parameters)
{ Statement(s);
...
return value;
}
|
 |
|
|
The header of the method consists of the following sections:
|
|
| section #1 |
section #2 |
section #2 |
section #4 |
section #5 |
| access
rights |
scope of
method |
return type
|
method
name |
(parameter list)
|
|
|
| Here is an explanation of the sections of a header: |
|
| Section |
Valid
values |
Explanation |
| access rights |
public
or
private |
This section specifies whether any method
can access the method (public) or only methods in the
same class are allowed to access it (private) |
| scope |
static
or
no scope is specified |
When a method is declared as static
only one method of this name is available any object instantiated from
this class, no matter how many there are.
If it is not declared as static, each object that is instantiated from
this class has its own copy of this method.
Note static methods
cannot make use of non-static methods but non-static methods can make
use of static methods. |
| return type |
any valid data type
or Class type or void
(ie: int, double, String ...) |
This section specifies what kind of data (ie:
an int, String, float ...) is to be returned back after this method
has completed it's tasks. The void type means that this
method does not return any data, instead it does some job. |
| method name |
any valid name
(same rules as variable names) |
This section specifies the name of the
method. To invoke
a method, referring to method's name and specify which
parameters are to be sent to the method. |
| parameter list |
(
parameters in brackets )
or
( ) |
This section specifies the parameter list. Parameters
represent the data that is to be sent into the method. The data can
then be processed inside of the method when it is invoked. Methods are
allowed to take no parameters - but the ( ) braces
are still necessary as part of the method header. |
|
|
| The body of the method consists of the following sections: |
|
| { |
|
| |
Statement 1;
Statement 2;
return <some value>;
|
| } |
|
|
|
| Inside the body of the method, you can have Java statements,
expressions, calls to other methods within this class calls to public
methods in other classes, loops, and so on. |
| If the method has a return type (it has not been declared to return void),
then somewhere inside the body of the method you need to return a value. Use
the return keyword to do
this. |
|
| Methods must be declared before they are used. This is where
the use of the import statement comes into play (ie: import
java.io.*). Importing a library brings the methods of that library (the
method declarations) into your program (well, sort of, but not exactly- don't
worry about the details) so that you can invoke those functions later on in your
Java code. |
| A method is invoked
(called) from the main method or from some
other method in order to execute. |
|
| Sample declaration and use of a user-defined method: |
|
import java.io.*;
public class Methods_Sample
{
public static int doubleIt( int
x)
{
int y = x+x;
return y;
} // end "doubleIt"
method
public static void main (String[ ]
args)
{
int somenumber = 5;
int doublenumber;
doublenumber = doubleIt(
somenumber );
System.out.println("The Number is " + somenumber );
System.out.println("the Number doubled= " +
doublenumber);
} // end main method
} // end of class
|
|
| The above code has two methods, the main( ) method and
the doubleIt method. The main method makes a call to
the method doubleIt which executes and then
returns back an integer value based on the data passed into doubleIt (the parameter "x" holds that data). |
|
|
Try this
example to see how to get error checked decimal numbers from the user:
* This function takes NO parameters and
returns a value of the variable type double.
|
|
import java.io.*;
public class Class1
{
public static double getDoubleNumber( ) {
double answer = 0.0;
String temp = "";
DataInput keyboard = new
DataInputStream(System.in);
boolean okInput = false;
while ( okInput == false )
{
System.out.print("Enter a decimal number
please ");
try {
temp = keyboard.readLine( );
answer = Double.parseDouble(temp);
okInput = true;
} //
end try
catch (Exception e)
{
System.out.println("Improper
Input");
} //
end catch
} // end while loop
return answer;
} // end getDoubleNumber( )
function
public static void main (String[ ] args) {
double x, y, a, b, c ;
System.out.println("Value A for quadratic
equation");
a = getDoubleNumber( );
System.out.println("Value B for quadratic
equation");
b = getDoubleNumber( );
System.out.println("Value C for quadratic
equation");
c = getDoubleNumber( );
System.out.println("Value X for quadratic
equation");
x = getDoubleNumber( );
y = a*x*x + b*x + c;
System.out.println("Y Value for quadratic =" + y);
} // end main method
} // end of class
|
|
|
Try this
example to see how to get error checked decimal numbers from the user:
* This function takes ONE String parameter and
returns a value of the variable type double.
|
|
import java.io.*;
public class Class2
{
public static double
getDoubleNumber(String UserMessage) {
double answer = 0;
String temp = "";
DataInput keyboard = new DataInputStream(System.in);
boolean okInput = false;
while
( okInput == false) {
System.out.print(UserMessage);
try {
temp = keyboard.readLine( );
answer = Double.parseDouble(temp);
okInput = true;
} //
end try
catch (Exception e) {
System.out.println("Improper
Input");
} // end catch
}
// end while loop
return answer;
} // end
getDoubleNumber( )
function
public static void main
(String[ ] args) {
double x, y, a, b, c ;
a = getIntegerNumber("Value A for quadratic
equation" );
b = getIntegerNumber("Value B for quadratic
equation" );
c = getIntegerNumber("Value C for quadratic
equation" );
x = getIntegerNumber("Value X for quadratic
equation" );
y = a*x*x + b*x + c;
System.out.println("Y
Value for quadratic =" + y);
} // end main
method
} // end of class
|
|