Overview

From CompSciWiki
Revision as of 14:36, 14 March 2007 by Ummisur0 (Talk | contribs)

Jump to: navigation, search

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 accepts three parameters (firstNum, secondNum, thirdNum), calculates the average of these three numbers, then 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.

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.

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.

Try running a program without a main method and see the result.