Overview

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > User-Defined Methods

Introduction

All of the code you have written up until now has been placed in the main method. As your programs get larger, code written entirely in the main method becomes difficult to maintain and understand. This chapter will explain how to define separate code sections called user-defined methods, which perform specific tasks. These code sections may then be used repeatedly, any number of times.


What is a User-Defined Method?

A user-defined method is a section of code which is declared and written somewhere in your class, then called from anywhere else in your program. Instead of writing an entire program in the main method, you can separate program functionality into separate logically separated user-defined methods. Doing so has two main benefits:

  1. Readability - User-defined methods will allow a programmer reading code to understand, at a glance, the main purpose of the program. The programmer will quickly be able to comprehend what the user-defined method does, without needing to worry about how it is implemented.
  2. Re-usability - When a program consists of only a main method, code can only be reused by copying and pasting sections. On the other hand, if a program is logically split up into a number of user-defined methods, the programmer can call these methods from other programs, or easily fit them into pre-existing code.

A method does three things:

  1. Accepts input values, called parameters.
  2. Performs a single task, which may use the parameters.
  3. Gives a return value, or output value, to the code which called the method.


The following is an example of a user-defined method:

 public static int getAverage(int firstNum, int secondNum, int thirdNum)
    {
        int average;
        average = (firstNum + secondNum + thirdNum) / 3;
        return average;
    } 

Above is a method called getAverage. The method does three things:

  1. Accepts three parameters (firstNum, secondNum, thirdNum)
  2. Calculates the average of these three numbers
  3. Returns the average as the method result.


An Analogy

Steve is setting up his apartment for a party on Friday. He goes through his checklist of things to do:

  • Move the furniture
  • Set up the stereo
  • Buy some chips
  • Pay for the pay-per-view fight
  • Clean the bathroom

Steve begins by moving his furniture so that there will be plenty of room for his guests in his small apartment. He hooks up his stereo with giant subwoofers to ensure that the neighbours will complain about the racket at 2:00 in the morning.

Next, Steve needs to pick up some chips, but he doesn't feel like going out shopping. He isn't even sure which would be the best brand to purchase.

"I should get my brother Greg to go pick up the chips," Steve decides.

So Steve called his brother. "Greg! Could you get the chips for tonight? Preferably two bags of spicy tortillas?."

Greg, being the great brother he is, heads out to the nearest convenience store and picks up two bags of jalapeno-cheddar tortillas. Meanwhile, Steve has been working all day, and believes he has earned a break until Greg gets back.

Upon returning home, Greg gives the chips to Steve. "I tried some of these chips last week," Greg says. "They're really great". Steve dumps the chips into bowls and places them on the table.

Steve now continues to prepare for the party. He phones the cable company and orders the pay-per-view fight, and then heads off to clean the bathroom.

How the Story Relates to User-Defined Methods

Steve's list of things to do are similar to computer instructions. His plan is to go through each step in the order he determined earlier, which is similar to how a Java program runs. First he moved the furniture, and then he set up the stereo.

But when it came time to buy the chips, he didn't want to complete the step himself. Instead, he got his brother to do it. In Java, having some other part of a program complete a series of instructions for you is known as calling a method. This chapter will explain how to write your own user-defined methods and how to call them.

Method Terms Related to Analogy

  • Defining the method
    • Greg is capable of doing many things, one of which is "Buying chips."
    • In Java, you may define a number of methods within any class you write.
  • Accepting parameters
    • Greg needed to know what kind of chips to buy, and how many bags he should purchase. Whenever somebody asks Greg to buy chips, that person will have to give him those two pieces of information.
    • In Java, a method definition states the parameters which the method requires to execute.
  • Passing arguments to a method
    • Steve tells Greg that he needs two bags of spicy tortillas. "Two bags" and "spicy tortillas" are the arguments.
    • In Java, when a user-defined method is called, the caller method must pass a value for each parameter to the called method. Each passed value is known as an argument.
  • Calling a method
    • Once Steve is finished setting up the stereo, he asks Greg to buy chips, and specifies both the amount and type of chips.
    • In Java, a method may be called at any point in your code. The method call consists of the name of the class where the method is defined, the method name, and a list of arguments. Your program waits for the method to complete execution, then the program continues on.
    • NOTE: If the called method is defined in the same class as the calling method, you do not need to specify the class name in the method call.
  • Performing some actions
    • Greg gets into his car, drives to the convenience store, buys the chips, and then drives back home.
    • In Java, the body of a user-defined method definition contains code which executes in order once the method is called.
  • Returning a result
    • Greg comes home with two bags of chips and hands them to Steve who has been taking a break since Greg left. Once Steve gets the chips from Greg, he stores them in bowls on the table.
    • In Java, once a called method is finished execution, it may return a value to the caller. The caller usually assigns this value to a variable that is used later, and then continues execution of its own code once the method call is complete.


The Main Method

Up until now, you have placed all code inside the main method like so:

 public static void main(String[] args)
    {
        // Code is written here
    } 

The main method is a special type of user-defined method. When you tell Java to run your program, Java will look for a method called main within your class and run the method if found. As proof, try running a program without a main method and note the result.