Lesson: Method Structure

Overview: 
Explore the structure of methods and how they are defined.
Objectives: 

Understand the structure of methods, the method header and how to write methods.

Content: 

The form of a method is:

The components are:

  • modifiers control access to methods and other special effects on methods. Modifiers will be discussed later. For now just use the word public.
  • return-type defines the data type of the method's return value if any. If there is no return value, use the word void. At a basic level, a return value is what the function will give back to us when it’s done running. We will discuss return values in the next lesson.
  • name is the name of the method. It is case sensitive.
  • parameter-list is an optional comma separated list of data values to be passed from the calling code to the method for its internal use. These are the inputs to the function, like the x in f(x). If no parameters use empty parenthesis. Parameters will be discussed shortly.
  • exception-list is a list of possible errors (called exceptions) the method might generate. We will discuss exceptions in an advanced lesson.
  • statements is one or more variable definitions or statements that make up the body of the method, and determine what the method actually does.

The name and parameter list are used by the compiler to determine which method is which and the two together are called the method signature. When called, the statements inside a method's curly braces (the method body) are executed one after another until the end of the method body is reached. You can end method execution prior to the end of  the body with the return statement.

Variables defined inside a method (called local variables) can only be accessed in that method. Global variables, that is variables defined in the class that contains the method, are accessible in the method.

Methods are called by using the method signature (name and any parameters) in a statement.

Lets look at an example (ignore the static modifier and args parameter for now):

This program will print out "Hello World! 15" two times. The JVM will start the program by calling the main() method. The main method calls myMethod() twice. myMethod() calls myMethod2() passing in the value in variable x and gets back the result of the computation in myMethod2(). That result is then stored in x in myMethod(). This is a pretty simple example but shows how the processing in the methods myMethod() and myMethod2() are easily used by calling code. As we learn more about methods we will see how useful they can be and how they are the cornerstone of object based programming.

Here is this example in CodingGround. Modify the example to add a new method whose name is your first name. Have that method print out Hello followed by your name.
 
 

Navigation: