COMP2243 - Programming and Problem Solving

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Methods RightTriangle.java RightTriangleWithLoop.java Geometry.java PayrollWithMethod.java PayrollWithMethodLoop.java Palindrome.java GlobalAndLocal.java Overloading.java Overloading2.java MathMethods.java and MathProgram.java CaesarCipher.java



Methods (Procedural Programming)


In Chapter 5, we study how to define and call methods in the program.

Introduction to Methods

So far, all the programs we studied use only the main() method.

Java statements are packed into the main() method.

This technique is appropriate only for small programs, but not practical for large programs.

The analogy is that a company has only one person, the boss.


In this section, we learn how to use methods to break the program into small manageable pieces called methods.

This approach is called divide and conquer strategy.

Methods can simplify programs.

Methods are reusable. If a specific task is expected to be performed in several places in the program, we can write one method which include the code to perform that task, and then call the method anytime the task is performed.

The analogy is that a company hires employees and each employee is to perform his/her job duty. The boss calls the employee anytime the desired job is expected to be performed.



Predefined Methods

Java has a large collection of predefined methods.

We have used some of them.

Examples:

System.out.println("Hi!");

int number = Integer.parseInt("700");

double result = Math.pow (2.5, 3.5);

In this section, we learn how to create programmer-defined methods.

Method Signature



public: the method is publicly available to code outside the class.

static: the method belongs to a class, not a specific object.

return type: the data type of the returned value. For example: int, double, String, boolean, and etc.
(If the method does not return anything, the return type is void.)

method name: a unique name for the method.

parameters: data items needed to perform the task.

Two steps to incorporate methods in the program

Step 1: Define the method

Step 2: Call the method

Variable Scope - Global variable vs. Local Variable

Global variables:

Global variables are declared outside of any method. They are accessible to every method in the program.

Using global variables is considered as the bad programming practice and strongly discouraged.

Only global variable should be used is the keyboard.

Other global variables are not acceptable in COMP 2243.

Local variables:

Local variables are declared inside a method and is not accessible to statements outside the method.

Different methods can have local variables with the same names because the methods cannot see each other’s local variables.

A method’s local variables exist only when the method is executing. When the method ends, the local variables and parameter variables are deleted, and any stored values are lost.

Local variables are not initialized with default values and must be assigned to appriopriate values before they can be used.

Global Constant

Constants should be defined as global, because they are not changeable.

Method Definition

public static double hypotenuse(double s1, double s2) {

     double s3;

     s3 = Math.sqrt( Math.pow(s1,2) + Math.pow(s2, 2));

     return s3;
}

This method is a public static method.

The name is hypotenuse and it has two parameters which represent the side 1 and side 2 of a right triangle.

It returns a double value.

Basically this method calculates the hypotenuse of a right triangle based on the values stored in parameters.

Then it returns the result.

Calling Method

import java.util.Scanner;

public class RightTriangleProgram {

     //global variables are static
     static Scanner keyboard = new Scanner( System.in ); //global variable

     public static void main(String [] args) {

          double side1, side2, side3; //local variables to main() method

          System.out.print("Enter side 1: ");
          side1 = keyboard.nextDouble();

          System.out.print("Enter side 2: ");
          side2 = keyboard.nextDouble();

          //call hypotenuse method and pass arguments
          side3 = hypotenuse( side1, side2 );

          System.out.printf("%nSide 3: %.2f", side3);

     }//end main

} //end class

To call a method, simply call its name and pass the arguments inside the parentheses.

When passing the argument, just pass the name of the variable or the actual value. No data type is needed.

If the method returns a value, we can use a variable to store the returned value.

Arguments and Parameters

Arguments are the data values passed to the method by the caller.

Parameters are the data values received in the method signature and listed inside () after the method name.

Arguments and parameters have one-to-one match.

For example, if the method has two parameters, int and String, then the caller must pass an integer value and a string object in the correct order.

Method Overloading

If two or more methods have the same name in the same program, then they must have different parameter lists.

Different number of parameters or

Different data type of parameters or

Different order of parameters

Example:

public static void method1( int x, String y, double z) {}

public static void mehtod1( int x, int y ) {}

public static int method1( String s, int n, double x ) {}