Difference between revisions of "Overview"

From CompSciWiki
Jump to: navigation, search
(Overview of User-Defined Methods)
Line 27: Line 27:
 
# '''Returns''' the average as the method result.
 
# '''Returns''' the average as the method result.
  
The method does not run until some other piece of running code calls the method. The keywords '''public''' and '''static''' are always placed in front of method definitions, but '''the meanings of these keywords will not be explained in this course'''. Simply knowing that you need these keywords is sufficient for this course.
+
The method does not run until some other piece of running code '''calls''' the method. The keywords '''public''' and '''static''' are always placed in front of method definitions, but '''the meanings of these keywords will not be explained in this course'''. Simply knowing that you need these keywords is sufficient for this course.
  
 
Instead of writing an entire program in the main method, you can separate program functionality into separate user-defined methods. Doing so has two main benefits:
 
Instead of writing an entire program in the main method, you can separate program functionality into separate user-defined methods. Doing so has two main benefits:

Revision as of 20:45, 18 March 2007

Overview of User-Defined Methods

A user-defined method is a section of code which is declared once in a program, then used by other code sections.

A method does three things:

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

Here is an example of a user-defined method. Don't worry if you don't understand this - we will explain methods in more detail throughout the chapter:

    public static int getAverage(int firstNum, int secondNum, int thirdNum)
    {
        int average;

        average = (firstNum + secondNum + thirdNum) / 3;

        return average;
    }

The above is the definition of 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.

The method does not run until some other piece of running code calls the method. The keywords public and static are always placed in front of method definitions, but the meanings of these keywords will not be explained in this course. Simply knowing that you need these keywords is sufficient for this course.

Instead of writing an entire program in the main method, you can separate program functionality into separate user-defined methods. Doing so has two main benefits:

  1. Code becomes easier to read. When a complex code segment is placed in a user-defined method and called by the main method, a programmer who reads the main method will only need to understand what the user-defined method does, and not how it is implemented.
  2. Code becomes easier to reuse. When a program consists of only a main method, the only way to reuse sections of code is to copy and paste code sections. On the other hand, if a program separates its logic into a number of user-defined methods, the programmer can call these methods from other programs.

An Analogy

Billy 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

So he moves his furniture so that there's plenty of room in his small apartment. He hooks up his stereo with giant subwoofers so that the neighbors will complain about the racket at 2:00 in the morning.

Next, he needs to pick up some chips. But he doesn't feel like going out shopping, and besides, he doesn't even know the best brand to get.

"I should get my brother Jimmy to go pick up the chips," Billy decides.

"Jimmy!" Billy shouts. "Could you get the chips for tonight? Preferably two bags of spicy tortillas?"

Jimmy, being the great brother that he is, heads out to the nearest convenience store and picks up a few bags of jalapeno-cheddar tortillas. He heads home and hands the bags over to Billy. "I tried some of these chips last week," Jimmy says. "They're really awesome."

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

How the Story Relates to User-Defined Methods

Billy'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, 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, 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
    • Jimmy is capable of doing many things, one of which is "Buying chips."
    • In Java, methods may be defined in any class you write.
  • Accepting parameters
    • Jimmy needed to know what kind of chips to buy and how many bags to buy. Whenever somebody asks him to buy chips, that person will have to give Jimmy those two pieces of information.
    • In Java, a method definition states the parameters which the method requires to execute.
  • Passing arguments to a method
    • Billy tells Jimmy that he needs three bags of spicy tortillas. "Three 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 Billy is finished setting up the stereo, he asks Jimmy to buy chips and specifies 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
    • Jimmy gets into his car, drives to the convenience store, picks up the chips, pays for the chips, and drives back home.
    • In Java, the body of a user-defined method definition contains code which executes once the method is called.
  • Returning a result
    • Jimmy comes home with three bags of jalapeno-cheddar tortillas and hands them to Billy.
    • 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. The caller continues execution of its own code once the method call is complete.

An Example - 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.