Workshop 2007 JRE Java Support
Installation
Home
CalcTool
Java Applets
Friends/Family
Gardening
Woodworking
Forums

A method is a subroutine that does something.  For example, we may want to define and evaluate a function a.  We will utilize a method to evaluate this function and return the answer to a user-specified location.

 

Methods must be declared in the main body of your program. 

 

This means they will never be declared in your computeButtonMouseClicked()method, nor in any other method.

In general, methods have the form

<return type> methodName(<type> argument 1, <type> argument 2, …){
      //code goes here
      return answer of type <return type>;
}

<return type> can be any type of variable or object, such as double, int , boolean , etc.  You may even have a return type of void .  This means that the method does something, but returns nothing.  In the case of a void method, the last line,

return answer of type <return type>;


cannot be used.

Here’s an example of a method that calculates a.  In order to do this, we will need to input x as a double and return the answer as a double.  So the method might look like:

double f(double x){
double answer=Math.sin(x)*Math.sin(x);    //note the use of the
                                          // Math class here.
                                   // It has lots of functions!
return answer;
}

If we wanted to calculate a in the context of our computeButton method and put the result in the variable funcAnswer we would do this by

double funcAnswer=f(Math.PI/4.0);

Some other Math functions and constants can be found here.

 

 

See Sample Code 3 to check work

 

 

See Sample Code 4 to check work

 

 

Methods in Java