Introduction to Java using NetBeans

Section 2 - User Defined Methods


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.


Naming a Method

Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:



Simple Methods without Parameters


Assignment 2.9 Methods

Combine assignments 2.1 - 2.8 into one project. Each assignment should be it's own method. Call each method. Add a println to indicate which method is running.