6: Methods

What We Will Cover


Continuations

Homework Questions?

  • A4: Tally Ho! (10/4/04)
    Exercise 5 and CodeLab Lesson 5 (10/4/04)

Questions from last class?

Counter-controlled repetition requires:

  1. A named control variable and initial value.
  2. A control variable increment.
  3. A condition that tests for the final value of the control variable.
  4. All of the above.

6.1: Predefined Methods

Objectives

At the end of the lesson the student will be able to:

  • Call predefined methods
  • Generate random numbers

6.1.1: About Methods

Method -- a subprogram (function, procedure or subroutine) that executes a piece of code when called.

  • Java comes with libraries of predefined methods such as sqrt()
    • Math.sqrt(9.0) is a method call
    • A method call can be used like any expression
  • Predefined methods are found in libraries of classes
  • Java refers to these libraries as packages
  • Some packages must be “imported” into a program
  • import javax.swing.JOptionPane;

6.1.2: Calling Methods

  • Similar to a boss (calling method) asking a worker (called method) to complete a task
  • Methods are invoked by a method call
  • Arguments are used to send information to a method
  • Methods may or may not return a result to the calling method
  • After the method is finished, the program continues at the line after the call
  • You can use a method anyplace where it is legal to use its return type

Example Method Calls

    double result = Math.pow(2, 3);  // result is 8.0
    double num = -2.0;
    double value = Math.abs(num);    // value gets 2.0
    double stuff = 3 * Math.pow(2, 4) + 7;
    

6.1.3: Generating Random Numbers

  • Random numbers are a series of numbers whose order cannot be predicted
  • Many computational problems need to use random numbers
  • Hard to find truly random numbers, even in real life
    • Dice never perfect
    • Cards never shuffled completely randomly
    • Computers can only handle numbers within a finite range and limited precision
  • Best that can be done in most cases is generate psuedorandom numbers
    • Sufficiently random for the task at hand
  • Math.random() is a library method that produces series of psuedorandom numbers
    • Range is 0.0 up to, but not including, 1.0
    • Returns a double-precision value

Scaling and Shifting

  • Since the range of Math.random is between 0.0 and 1.0, will need to scale for your application
  • Also may need to shift the starting point of the numbers
  • General form for producing integer random numbers for an application:
  • STARTING_VALUE + (int) (Math.random() * SCALING_FACTOR);
    
  • For example, to simulate a single die with random numbers:
  • int die = 1 + (int) (Math.random() * 6);
    System.out.println("You rolled a " + die);
    

6.1.4: Dice Simulation

  • Let us use random numbers to simulate die rolling
  • public class DieRoller {
        public static final int STARTING_VALUE = 1;
        public static final int SCALING_FACTOR = 6;
    
        public static void main(String[] args) {
            int die = STARTING_VALUE
                + (int) (Math.random() * SCALING_FACTOR);
            System.out.print("You rolled a " + die);
            die = STARTING_VALUE
                + (int) (Math.random() * SCALING_FACTOR);
            System.out.println(" and a " + die);
        }
    }
    
  • Note how the program simulates rolling 2 dice

6.1.5: Summary

  • A method is a block of code get executed when called
  • Java has many predefined methods in several libraries
  • Some libraries must be "imported" into a program
  • import java.text.NumberFormat;
  • Some of the library methods generate "random" numbers
  • We can use these methods to simulate the rolling of a die
  • int die = 1 + (int) (Math.random() * 6);
    System.out.println("You rolled a " + die);
    

Exercise 6.1

  1. Start a text file named exercise6.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 6.1
  4. Complete the following specifications.

Specifications

  1. Update the program shown below that simulates rolling two dice.
  2. Use a loop to roll the two dice 10 times, displaying the output each time.
  3. Submit your final program along with your exercise6.txt file.
public class DieRoller {
    public static final int STARTING_VALUE = 1;
    public static final int SCALING_FACTOR = 6;

    public static void main(String[] args) {
        int die = STARTING_VALUE
            + (int) (Math.random() * SCALING_FACTOR);
        System.out.print("You rolled a " + die);
        die = STARTING_VALUE
            + (int) (Math.random() * SCALING_FACTOR);
        System.out.println(" and a " + die);
    }
}

6.2: Coding Methods

Objectives

At the end of the lesson the student will be able to:

  • Declare and define methods
  • Pass values to methods
  • Return a value from a method
  • Trace method calls
  • Describe what is meant by a local variable

6.2.1: Defining Methods

Why Define Methods?

  • Methods allow grouping of related code that performs specific task
  • Aids in structuring code
  • Makes program development more manageable
  • Makes it easier to reuse sections of code
  • Rule of thumb: If you repeat the same sequence of 3 or more lines more than once, you should create a method for the task performed.

  • Methods allow you to break big problems down into smaller subproblems
  • After solving the subproblems, all you need to do is fit the pieces together

Coding Methods

  • Programmers can write customized methods
  • Syntax:
  • static returnType methodName(parameterList) {
        ...
    }
    
  • Begins with the data type of the value that will be returned
    • Can be any primitive type (char, int, double, etc.) or class (String, etc.)
    • When no values are returned, use the special type: void
  • After specifying the data type, give the method a name
  • Following the name, add a set of parentheses ()
  • Within parenthesis are parameters that receive any passed arguments
  • Code executed by the method is enclosed in brackets {...}
  • After the method is finished, program continues at the line after the call
  • Can use a method anyplace where it is legal to use its return type

For Example

  • Following code has two methods
  • public class Square5 {
        public static void main(String[] args) {
            double result = square(5);
            System.out.println(result);
        }
    
        static double square(double x) {
            return x * x;
        }
    }
    
  • Method main calls method square, passing an argument of 5
  • Method square takes the argument, computes the squares and returns the result
  • Programming style: note the placement of the curly braces

Programming Style: Method Naming Conventions

  • Use verbs to name methods, since they perform an action
  • Start method names with a lower case letter
  • Further information: The Java Language Specification: 6.8.3 Method Names
  • Block comments: Javadoc before method names
  • OK if formal parameter names are the same as argument names

Static Methods

  • Until we cover objects, all our methods must use the qualifier static
  • If you forget the static keyword, you get a message like:
non-static method cannot be referenced from a static context

6.2.2: Passing Values

  • Passing values to methods increases their usefulness and flexibility
  • Input values for methods are called parameters or passed values
    • Within the method, the values that are passed are called parameters
  • Can specify zero, one or more parameters for a method
  • Definition of method must specify data types and names
    • Note that parameters look like variable declarations
    • Difference is that parameters are initialized by arguments
  • Separate multiple parameters with a comma
  • returnType methodName(Type1 param1, Type2 param2, ...) {
        ...
    }
    
  • Calling method must put values of the same data type, in the same order, inside the parentheses

For Example

  • Following program has a method for calculating powers of numbers with positive exponents
import javax.swing.JOptionPane;

public class Power {
    public static void main(String[] args) {
        String in;
        int base, exp;

        in = JOptionPane.showInputDialog("Enter base int");
        base = Integer.parseInt(in);
        in = JOptionPane.showInputDialog("Enter exponent");
        exp = Integer.parseInt(in);

        long value = pow(base, exp);
        System.out.println(value);

        System.exit(0);
    }

    static long pow(int base, int exponent) {
        long power = 0;
        if (exponent == 0) {
            return 1L;
        } else if (exponent > 0) {
            int loopCounter = 1;
            power = base;
            while (loopCounter < exponent) {
                power = power * base;
                loopCounter++;
            }
        }
        return power;
    }
}

6.2.3: Returning a Value

Return Statement

  • Methods that return a value must execute a return statement
  • Must return a value unless defined with a void return-type
  • For example:
  • import javax.swing.JOptionPane;
    
    public class Power {
        public static void main(String[] args) {
            String in;
            int base, exp;
    
            in = JOptionPane.showInputDialog("Enter base int");
            base = Integer.parseInt(in);
            in = JOptionPane.showInputDialog("Enter exponent");
            exp = Integer.parseInt(in);
    
            long value = pow(base, exp);
            System.out.println(value);
    
            System.exit(0);
        }
    
        static long pow(int base, int exponent) {
            long power = 0;
            if (exponent == 0) {
                return 1L;
            } else if (exponent > 0) {
                int loopCounter = 1;
                power = base;
                while (loopCounter < exponent) {
                    power = power * base;
                    loopCounter++;
                }
            }
            return power;
        }
    }
    
  • Method pow uses a return statement because it returns a value
  • Method main does not return a value
    • Return statement is optional if no value is returned
    • Return occurs automatically at the end of the method

Exiting Early

  • Sometimes do not want to execute all the code in a method
  • Can use return statement to stop execution and return from anywhere
  • Control returns immediately from a method when a return is executed

6.2.4: Methods Calling Methods

  • Methods may call other methods
  • Within the body of the method, you can code another method call
  • We are already doing this when main() calls another method
  • A method can even call itself
    • Known as recursion
    • Will cover later in the course

6.2.5: Tracing a Method Call

  • When methods call methods, you still need to follow the flow of execution
  • A method call transfer control to the first statement of the called method
  • When a return point is reached, control passes back to the point right after the method call
    • Return statement
    • End of method
  • If the method returns a value, that value is substituted for the method call
  • Let's trace the flow in the following code:
  • import javax.swing.JOptionPane;
    
    public class Power {
        public static void main(String[] args) {
            String in;
            int base, exp;
    
            in = JOptionPane.showInputDialog("Enter base int");
            base = Integer.parseInt(in);
            in = JOptionPane.showInputDialog("Enter exponent");
            exp = Integer.parseInt(in);
    
            long value = pow(base, exp);
            System.out.println(value);
    
            System.exit(0);
        }
    
        static long pow(int base, int exponent) {
            long power = 0;
            if (exponent == 0) {
                return 1L;
            } else if (exponent > 0) {
                int loopCounter = 1;
                power = base;
                while (loopCounter < exponent) {
                    power = power * base;
                    loopCounter++;
                }
            }
            return power;
        }
    }
    

6.2.6: Local Variables and Scope

  • Scope determines where you can access a variable
  • Variables defined in methods can only be accessed within that method
  • Local variables and method parameters can only be accessed within their block
  • Blocks begin at opening brace ({) and ends at closing brace (})
  • In general, variables declared inside a block are known only inside that block
  • When the block finishes executing, local variables disappear
  • References to local variables outside their block cause a compile error
  • Also note that parameters are just local variables with a special initialization mechanism

For Example

  • What is displayed by the following code??
  • public class ScopeTester {
        public static void main(String[] args) {
            double x2 = 2.0;
            square(x2);
            System.out.println("x^2 = " + x2);
        }
    
        static void square(double x) {
            double x2 = x * x;
            System.out.println("x^2 = " + x2);
        }
    }
    
  • How could you fix the problem?

Class Constants Revisited

  • Available to all methods
  • Declared outside any method body but within a class
  • Usually declared as: public static final
  • Can be accessed outside of a class by prepending the class name
import javax.swing.JOptionPane;

public class Sphere {
    // Class constant
    public static final double PI = 3.14159;

    public static void main(String[] args) {
        double radius, areaOfCircle, volumeOfSphere;
        String input, output, message;

        message = "Enter a radius to use for both\n"
                  + "a circle and a sphere (in inches)";
        input = JOptionPane.showInputDialog(message);
        radius = Double.parseDouble(input);

        areaOfCircle = area(radius);
        volumeOfSphere = volume(radius);

        output = "Radius = " + radius + " inches\n"
                  + "Area of circle = " + areaOfCircle
                  + " square inches\n"
                  + "Volume of sphere = " + volumeOfSphere
                  + " cubic inches\n";
        JOptionPane.showMessageDialog(null, output);

        System.exit(0);
    }

    public static double area(double radius) {
        return (PI * Math.pow(radius, 2));
    }

    public static double volume(double radius) {
        return ((4.0 / 3.0) * PI * Math.pow(radius, 3));
    }
}

About Global Variables

  • Java does not support global variables
  • Usually a bad idea to use one anyway
  • Makes programs more difficult to understand and maintain

6.2.7: Summary

  • Methods are declared by specifying a return type, name and a list of parameters
  • static returnType methodName(Type1 param1, Type2 param2, ...) {
        ...
    }
    
  • Values are passed to a method by putting values of the same data type, in the same order, inside the parentheses
  • methodName(arg1, arg2, ...);
  • Values are copied from the arguments to the parameters when the method is called
  • Methods return a value of the type declared
    • When returning nothing, special return type of void is used
  • To return a value, use a return statement
  • return returnValue;

Exercise 6.2

  1. Label this exercise: Exercise 6.2
  2. Submit all exercises for this lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exercise6.txt.

Specifications

The absolute value of a number is the number itself if the number is positive and the negative of the number if the number is negative. For instance, the absolute value of 1 is 1 and the absolute value of -1 is also 1.

  1. Write a program with a method named calcAbs() that accepts a parameter of type double, computes the absolute value of the parameter, and returns the absolute value.
  2. Submit your final program along with your exercise6.txt file.
  3. Record answers to the following questions in exercise6.txt.
  4. Q1: What is the absolute value of 4?

    Q2: What is the absolute value of -4?

    Q3: Which line number of your program calls the calcAbs() method?

    Q4: How did your method return the results of the computation?

You can use the following code to get started.

import javax.swing.*;

public class AbsValueMaker {
    public static void main(String[] args) {
        double num = 0.0;
        String in, out;

        in = JOptionPane.showInputDialog("Number to convert:");
        num = Double.parseDouble(in);

        out = "Absolute value is: " + calcAbs(num);
        JOptionPane.showMessageDialog(null, out);

        System.exit(0);
    }

    public static double calcAbs(double value) {
        // Insert statements here
        return 0;
    }
}

6.3: Developing, Testing and Debugging Methods

Objectives

At the end of the lesson the student will be able to:

  • Describe how to design methods
  • Code driver methods
  • Code stub methods

6.3.1: Designing Methods

  • Methods are subprograms whose purpose is to transform data
  • As subprograms, they usually receive inputs and produce outputs
  • Methods transfer data

  • Examples of methods include:
    • Converting keyboard entries into letters and numbers
    • Changing ounces to millimeters
    • Converting data into a report displayed on the screen

Method Content

  • A method is like a paragraph in a writing
  • Each paragraph should discuss one topic
  • Similarly, each method should do only one thing and do it well
  • The method's name should describe that action
  • You should try to develop one method for each conceptual activity in your program
  • All the statements in a method should focus on doing that one thing

Input and Output

  • When you organize your code into methods, you want them to be as independent from one another as possible
  • To create this independence, you control the inputs and outputs
  • A method can get input from many sources
    • Arguments from the method call
    • Constants from outside the method
    • Keyboard or another device
  • Similarly, a method can express its output many places
    • Return a value
    • Display information to the screen
    • Alter data passed as references (cover later)
    • Alter instance variables (cover later)
  • Your method should take as input only data needed by the method
  • Output from the method should only be the actual data produced by the method

6.3.2: Implementing Methods

  • Methods should be developed as self-contained modules
  • They can be designed and developed separately the from rest of program
  • Often, different methods are assigned to different programmers
  • All the programmers must understand how the methods are used
  • In addition, they must agree on the method interface

Method Interfaces

  • Most of the information for a method interface is contained in the header
  • static void performCalcuation(double dataToConvert)
    
  • If method and parameter names are chosen well, most programmers will understand the purpose of the method

6.3.3: First Implementation: Stubs

  • When you first implement a set of methods, it often makes sense to use stubs
  • Stubs are dummy methods that are called instead of the real method
  • They usually display a message acknowledging they were called
  • Sometimes they provide simple values for testing
  • Stubs should be so simple that you have confidence they will perform correctly

For Example

  • If a method does not have to return anything, you can code an empty method
  • static void performCalcuation(double dataToConvert) {}
    
  • If you want to see when a method is called, add a print statement
  • static void performCalcuation(double dataToConvert) {
        System.out.println("Executing performCalcuation");
    }
    
  • If the method needs to return a value, simply return a known value
  • static double transformValue(double in) {
        System.out.println("Executing transformValue");
        return 0;
    }
    
  • You can return later and write the complete method
  • Keep stubs so simple that you are confident they perform correctly
  • If stubs get too complex, it is better to just write the method
  • Once the methods are "stubbed out" you should develop a driver for testing

6.3.4: Drivers and Testing

  • Drivers are methods that send test data to all the other methods
  • Drivers allow you to test each method in your program
  • This enables you to complete each of your methods one at a time
  • Drivers should send both correct and incorrect data for testing
  • Once a method is tested, it can be used in the driver program to test other methods

For Example

  • Following is an example of a main method to drive the tests for the stubs shown above
public class Driver {
    public static void main(String[] args) {
        System.out.println("Calling performCalcuation");
        performCalcuation(1.0);

        System.out.println("Calling transformValue");
        double result = transformValue(1.0);
        System.out.println("  Result=" + result);
    }

    static void performCalcuation(double dataToConvert) {
        System.out.println("Executing performCalcuation");
    }

    static double transformValue(double in) {
        System.out.println("Executing transformValue");
        return 0;
    }
}

Coding Separate Test Programs

  • Driver programs are often coded in a separate class
  • This way you can keep the test code separate from the program code
  • An example of such a driver is the test file provided for the last assignment

Programming Style: Method Length

  • Methods that are too long are hard to understand
  • Long methods often mean you need to restructure your code into more methods
  • As a general rule, methods should be less than what will fit on one screen

6.3.5: Putting the Pieces Together

  • Once your methods work correctly, it is time to assemble the final program
  • You replace the driver code following the design of your program algorithm
  • Program development is an iterative process
  • You often have to make changes to previous code

Debugging the Program

  • Lots of output statements to trace the execution
  • Once developed, you remove all these statements before submitting

6.3.6: Summary

  • Methods are subprograms whose purpose is to transform data
  • Each method should do only one thing and do it well
  • To improve flexibility, your method should accept input from as few sources as possible
  • As you develop methods, you need to test each one individually
  • Drivers are used to test the individual methods
  • You should send both correct and incorrect data for testing
  • Once a method is tested, it can be used in the driver program to test other methods
  • Stubs are dummy methods that are called instead of the real method
  • They usually display a message acknowledging they were called
  • Sometimes they provide simple values for testing
  • Stubs should be so simple that you have confidence they will perform correctly
  • After your method work correctly, you replace the driver with the main program

Exercise 6.3

  1. Label this exercise: Exercise 6.3
  2. Submit all exercises for this lesson in one file unless instructed otherwise
  3. Spend 5 minutes reviewing the specification for the next assignment
  4. We will review the specification and work on the design together during this exercise.

  5. Record a description of the design in exercise6.txt.

6.4: Programming Style Reviewed

Objectives

At the end of the lesson the student will be able to:

  • Discuss the purpose of programming style
  • Use javadoc to document a class
  • Describe the programming style requirements to date

6.4.1: About Programming style

  • Programming style is about how you organize and document your code.
  • A program is written once, but read many times
    • During debugging
    • When adding to the program
    • When updating the program
    • When trying to understand the program
  • Anything that makes a program more readable and understandable saves lots of time, even in the short run
  • Programs written following a consistent style are:
    • Easier to read
    • Easier to correct
    • Easier to maintain
  • Java has introduced many innovations to programming style.
  • One such innovation was Javadoc
    • Automatically creates HTML explaining your code to other programmers
    • Based on code structure and programmer comments
    • Many other programming languages have emulated the Javadoc tool
  • Another important tool is CheckStyle
    • Automatically checks your code for conformance to style guidelines
    • Used in the grading process
  • We will discuss programming style and these tools in this section

6.4.2: Programming Style Requirements to Date

  • Below is a list of programming style requirements covered so far
  • Will have more as the course continues
  • Difficult to remember them all
  • Use CheckStyle to remind yourself of problems
    • Will cover using CheckStyle later today
  • Can also set your text editor to eliminate some problems automatically

Programming Style Topics to Date

  1. Use block comments at the start of a program (2.1.1)
  2. Line length (2.1.2)
  3. Identifiers have naming convention (2.1.3)
  4. Do not use tabs (2.2.5)
  5. Spacing required around operators (3.1.5)
  6. No spacing after opening or before closing parenthesis (3.1.5)
  7. Variable names have naming convention (3.2.2)
  8. Constant names have naming convention (3.2.3)
  9. No "magic" numbers (3.2.3)
  10. Curly braces in if-else statements (4.5.3)
  11. Curly braces in while statements (5.1.4)
  12. Curly braces in method definitions (6.2.1)
  13. Method names (6.2.1)
  14. Javadoc before method names (6.2.1)

6.4.3: Using Javadoc to Document a Class

Following is available from the How To Document and Organize Java Code.

6.4.4: Generating Documentation from Javadoc

  • Creating Javadoc
  • Can use a Web browser to view user-defined classes
  • Looks the same as the on-line Java API
  • Note: to run the Javadoc tool in the classroom, you will need to both save your source code and run the tool in the C:\TEMP directory.

6.4.5: Using CheckStyle

  • Cumbersome to check your code for programming style
  • Instead, you can use your computer to accomplish the task
  • Use a program named CheckStyle
    • Free and open source
    • Used for major Java projects like Jakarta
  • I provide instructions for installing and using CheckStyle for both jEdit and TextPad

6.4.6: Summary

  • Programming style is about how you organize and document your code.
  • Programs written following a consistent style are:
    • Easier to read
    • Easier to correct
    • Easier to maintain
  • Programmers use the documentation to understand how to use your code
  • You can use CheckStyle to automatically check many aspects of your programming style

Exercise 6.4

  1. Label this exercise: Exercise 6.4
  2. Submit all exercises for this lesson in one file unless instructed otherwise
  3. Complete the following and record the answers to any questions in exercise6.txt.

Specifications

  1. Document the following program and run CheckStyle to verify your documentation is correct. Save your documented program along with this weeks exercises.
  2. Create Javadoc on your properly-documented code. Save the Power.html file along with this weeks exercises.
  3. Note: to run the Javadoc tool in the classroom, you will need to both save your source code and run the tool in the C:\TEMP directory.

    Q1: Why should you document your code following standards?

    Q2: What is the purpose of an @param tag?

import javax.swing.JOptionPane;

public class Power {
    public static void main(String[] args) {
        String in;
        int base, exp;

        in = JOptionPane.showInputDialog("Enter base int");
        base = Integer.parseInt(in);
        in = JOptionPane.showInputDialog("Enter exponent");
        exp = Integer.parseInt(in);

        long value = pow(base, exp);
        System.out.println(value);

        System.exit(0);
    }

    static long pow(int base, int exponent) {
        long power = 0;
        if (exponent == 0) {
            return 1L;
        } else if (exponent > 0) {
            int loopCounter = 1;
            power = base;
            while (loopCounter < exponent) {
                power = power * base;
                loopCounter++;
            }
        }
        return power;
    }
}

Wrap Up

Home | WebCT | Announcements | Schedule | Expectations | Course info
Help | FAQ's | HowTo's | Links

Last Updated: October 06 2004 @19:24:12