Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use

What are Methods?

A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name.  Think of a method as a subprogram that acts on data and often returns a value.

Each method has its own name.  When that name is encountered in a program, the execution of the program branches to the body of that method.  When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code.

Good programmers write in a modular fashion which allows for several programmers to work independently on separate concepts which can be assembled at a later date to create the entire project.  The use of methods will be our first step in the direction of modular programming.

Methods are time savers, in that they allow for the repetition of sections of code without retyping the code.  In addition, methods can be saved and utilized again and again in newly developed programs.

You are using methods when you use
System.out.print( ) and System.out.println( ).

There are two basic types of methods: 

Built-in:  Build-in methods are part of the compiler package, such as System.out.println( ) and  System.exit(0).
User-defined: User-defined methods are created by you, the programmer. These methods take-on names that you assign to them and perform tasks that you create.

How to invoke (call) a method (method invocation):

When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc.  The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires.  The required data for a method are specified in the method's parameter list.

Consider this method that we have already been using from Breezy;

      int number = Console.readInt("Enter a number");  //returns a value

The method name is "readInt" which is defined in the class "Console".  Since the method is defined in the class Console, the word Console becomes the calling object.  This particular method returns an integer value which is assigned to an integer variable named number.

You invoke (call) a method by writing down the calling object followed by a dot, then the name of the method, and finally a set of parentheses that may (or may not) have information for the method.


  Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use