Overview

From CompSciWiki
Revision as of 20:09, 13 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.

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:

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 it if main is found. Try running a program without a main method and see what the result is.