STUDENT OUTLINE

Lesson 5 - More About Methods


INTRODUCTION:

Programs of any significant size are broken down into logical pieces called methods. It was recognized long ago that programming is best done in small sections which are connected in very specific and formal ways. Java provides the construct of a function, allowing the programmer to develop new methods not provided in the original Java libraries. Breaking down a program into blocks or sections leads to another programming issue regarding identifier scope. Also, methods need to communicate with other parts of a program which requires the mechanics of parameter lists and a return value.

The key topics for this lesson are:

A. Writing Methods in Java
B. Value Parameters and Returning Values
C. Lifetime, Initialization, and Scope of Variables

VOCABULARY:

METHOD DECLARATION
METHOD DEFINITION
PARAMETERS
FORMAL ARGUMENTS
SCOPE

VALUE PARAMETERS
ACTUAL ARGUMENTS
GLOBAL SCOPE
BLOCK
LOCAL SCOPE

DISCUSSION:

A. Writing Methods in Java

1. A method is like a box that takes data in, solves a problem, and usually returns a value. The standard math methods follow this pattern:

 Math.sqrt (2) --> 1.414

2. There are times when the built-in methods of Java will not get the job done. We will often need to write customized methods which solve a problem using the basic tools of a programming language.

3. For example, suppose we need a program that converts gallons into liters. We could solve the problem within the main method.

Program 7-1

import java.util.Scanner;

class GallonsToLiters
{
  public static void main (String[] args)
  {
    double gallons, liters;
    Scanner console = new Scanner();

    System.out.println("Enter an amount of gallons --> ");
    gallons = console.nextDouble();
    liters = gallons * 3.785;
    System.out.println("Amount in liters = " + liters);
  }
}

This works fine, but the mathematics of the conversion is buried inside the main method. The conversion tool is not available for general use. We are not following the software engineering principle of writing code that can be recycled in other programs.

4. Here is the same routine coded as a reusable method:

Program 7-2

import java.util.Scanner;

class FluidConverter
{
  public double toLiters(double gallons)
  {
    return gallons * 3.785;
  }
}


public class TestConverter
{
  public static void main(String[] args)
  {
    double gallons;
    Scanner console = new Scanner( System.in );
    FluidConverter convert = new FluidConverter();

    System.out.print("Enter an amount of gallons --> ");
    gallons = console.nextDouble();
    System.out.println("Amount in liters = " +
      convert.toLiters(gallons));
  }
}

Sample run output:

Enter an amount of gallons --> 10
Amount in liters = 37.85

5. Here is the sequence of events in this short program.

a.   Execution begins in the main method with the user prompt and the input of an amount of gallons.
b.   The toLiters method of the convert object is called and the amount of gallons is passed as an       argument to the toLiters method.
c.   Program execution moves to toLiters which solves the math and returns the answer to the calling       statement.
d.   The answer is printed out.

6. The general syntax of a method declaration is

<modifiers> <return type> <method name> ( <parameters> )
{
<method body>
}

a.   The <modifiers> refers to a sequence of terms designating different kinds of methods.
b.   The <return type> refers to the type of data a method returns. The data type can be one of the       predefined types (integer, double, char) or a user-defined type.
c.   The <method name> name is the name of the method. The name of the method must be a valid       identifier. In the case of Program 6-2, the names of the methods are main and toLiters.
d.   The <parameters> list will allow us to send values to a method. The parameter list consists of one       or more type-identifier pairs of information. These parameters are called the formal parameters.
e.   The <method body> contains statements to accomplish the work of the method.

7. When the method is called, the value passed to the method is called the actual parameter. The integer named gallons inside of the main method serves as the actual parameter.

B. Value Parameters and Returning Values

1. The values passed to a method become the source of input for the method. Notice that inside of toLiters, no data input was required from an external source.

2.The single parameter in Program 6-2, shown previously, is an example of a value parameter. A value parameter has the following characteristics:

a.    It receives a copy of the argument that was passed to the method. The value of 10 stored in        gallons (inside of main) is passed to the parameter amount (inside of toLiters).
b.    This value parameter is a variable that can be modified within the function.
c.    This value parameter is a local variable. This means that it is valid only inside of the block in which        it is declared. We refer to a method in Java as a block of code.

3. A method can return a single value. Somewhere in the body of the method there must be a return statement if we want the method to return the correct answer. A method that returns a value is also called a function.

4. If a method returns no value the term void should be used. For example:

public void printHello ( )
{
System.out.println("Hello world");
}

5. A function can have multiple parameters in its parameter list. For example:

public double doMath (int a, double x)
{
... code ...
return doubleVal;
}

When this method is called, the arguments fed to the doMath method must be of an appropriate type. The first argument must be an integer. The second argument can be an integer (which will be promoted to a double), but it will most likely be a double.

double dbl = doMath (2, 3.5); // this is okay
double dbl = doMath (1.05, 6.37); // this will not compile

6. Value parameters are often described as one-way parameters. The information flows into a function but no information is passed back through the value parameters. A single value can be passed back using the return statement, but the actual parameters in the function remain unchanged.

7. The actual arguments used to supply values for the value parameters can be either literal values (2, 3.5) or variables (a, x).

double dbl = doMath (a, x);    // example using variables

C.  Lifetime, Initialization, and Scope of Variables

1. Three categories of Java variables have been explained thus far in this curriculum guide.

  • Instance variables
  • Local variables
  • Parameter variables

2. The lifetime of a variable defines the portion of run time during which the variable exists.

a.   When an object is constructed, all its instance variables are created. As long as any part of the       program can access the object, it stays alive.
b.   A local variable is created when the program enters the statement that defines it. It stays alive until       the block that encloses the variable definition is exited.
c.   When a method is called, its parameter variables are created. They stay alive until the method       returns to the caller.

3. The initial state of these variables are also determined by their type.

a.   Instance variables and static variables are automatically initialized with a default value (0 for       numbers, false for boolean, null for objects) unless you specify another parameter.
b.   Parameter variables are initialized with copies of the actual parameters.
c.   Local variables are not initialized by default. An initial value must be supplied. The compiler will       generate an error if an attempt is made to use a local variable that has never been initialized.

 

4. Scope refers to the area of a program in which an identifier is valid and has meaning.

a.   Instance variables of a class are usually declared private, and have class scope. Class scope       begins at the opening left brace, {, of the class definition and terminates at the closing brace, }, of       the class definition. Class scope enables methods of a class to directly access all instance variables       defined in the class.
b.   The scope of a local variable extends from the point of its definition to the end of the enclosing       block.
c.   The scope of a parameter variable is the entire body of its method.

5. Example of the scope of the variable type is given in the program below.

Program 7-3

 

public class ScopeTest
{
  private int test = 30;
  
  public void printLocalTest()
  {
    int test = 20;   
    System.out.println("printLocalTest: test = " + test);
  }

  public void printInstanceTest()
  {
    System.out.println("printInstanceTest: test = " + test);
  }
  
  public void printParamTest(int test)
  {
    System.out.println("printParamTest: test = " + test);
  }

  public static void main (String[ ] args)
  {
    int test = 10;
    
    ScopeTest st = new ScopeTest();
    System.out.println("main: test = " + test);
    
    st.printLocalTest();
    st.printInstanceTest();
    st.printParamTest(40);
  }
}

Run output:

main: test = 10
printLocalTest: test = 20
printInstanceTest: test = 30
printParamTest: test = 40

 

SUMMARY/ REVIEW:

Your programs will grow in size and complexity. Initially you will not use all the tools presented in this lesson and other lessons regarding methods. However, you need to see and understand all the method-writing tools in Java since eventually you will need them in your own work and to help you read another programmer's code.

Back to Java Main Page