Java Lesson 10: Methods

2
20

Introduction

When writing a program, a situation often arises that can easily be handled by a method, which is a programming construct by which a specific task can be performed on more than one occasion. Similar to the procedures, subroutines, and functions in other programming languages, Java provides methods for this purpose.

Java allows programmers to define their own methods for carrying out various tasks. This tutorial focuses on the use and creation of methods.

Predefined Java-Provided Methods

Purpose

We are already familiar with some methods the Java environment includes to provide support for math functions, strings, input/output (I/O), windows graphics, networking, and time and date calculations, among many others. These are like (but not identical to) the C language stdio.h or the Python standard library. An example is Math.cos(x), which returns the cosine of the angle specified by x in radians.

Usage

To make use of or call a method, one needs only to write the name of the method followed by parenthesis enclosing the arguments and/or expressions for which the method is to be computed. For example, the following assignment statement containing the Math.cos() method

will cause the cosine of the angle x to be computed and the result assigned to the variable y.

More than one method can be called in a single assignment statement. For example, if you want to compute the cotangent of x, you could use the Math.cos() and Math.sin() methods, as in the statement

Any valid expression may be substituted for x in the methods. For example:

You can call a method inside of a loop. Program10a.java displays the sine of numbers from 0 through 10.


Compile and execute Program10a which displays the sine of numbers between 1 and 10.

Java’s methods can return Strings and other data types. An interesting application of this is Java Snippet: Display Your Operating System Name which calls the System.getProperty() method to return the name of the operating system your computer is running.

Programmer-Defined Static Methods

There are several kinds of methods which we will discuss in detail in the next lesson on Objects and Classes, but for now we will limit our discussion to static methods called from our main() program.

Purpose

Programmer-defined methods are a block of code written in such a way that it can only be executed when called by other code that is currently executing. A call to a method can be placed at any place in a program; that is, at different times and/or in different locations, a program may call upon a method to do an operation. When the statements in the method have finished executing, control returns to the caller via a return statement, and program execution resumes immediately after the point where the method was called. The method may be called several times. Methods offer a powerful means for accomplishing a very basic task in programming – using the same set of instructions repeatedly.

The use of programmer-defined methods promotes breaking down a large program into a number of smaller, self-contained components. Methods group related code together. Thus, you can modularize a Java program through the use of static methods.

There are several advantages to a modular approach. For example, many programs need a group of instructions to be executed repeatedly. The repeated instructions are placed within a single method, which can be called (invoked) when needed. Additionally, a different set of arguments can be passed to the method each time it is called. This reuse of a method avoids the need for duplicating the same set of instructions. Programs which contain methods are also easier to understand, because the programmer only needs to think about small chunks at a time instead of the entire program. Methods can be collected into libraries (packages) and shared with other programmers. These code in these methods are reused over and over.

Usage

The expression(s) inside the parenthesis are known as arguments. Arguments are always enclosed in parenthesis. Generally, a method will process information passed to it from the calling part of the program, and return a single value. Some methods, however, accept information but do not return anything. Methods can also be declared as having no arguments.

Creating Your Own Methods

Declare static methods in Java with a statement of the form:

Parameters are a comma-separated list which gives the method the information it needs.

The return type tells the Java compiler what type of value to expect. A method which does not return a value must be declared with a return type of void.

When called, the method executes until it reaches a return statement, whereupon it sends a value of the indicated type back to the point in the program where it was called from.

About static

The keyword static indicates that the method is the same for all classes. We will discuss static and the other method modifiers in Objects and Classes.

Our First Method: Area of a Circle

Suppose we wish to calculate the area of a circle. The formula is:

a = pi * r^2              // area equals pi times r-squared.

where a is the area of the circle, pi is 3.14159, and r is the radius of the circle.

Java provides the value of pi via the built-in constant Math.PI. We can code this formula in Java as:

While we could bury this formula in the middle of the main() method, we will write our own method called area():

Let’s look at this method line by line:

The first line declares a static method called area(). The method takes one argument, r, which is of type double. The method returns a result of type double.

The second line declares a working variable a of type double. This is a temporary variable to store an intermediate result. This variable is deallocated after the method exits.

The third line implements the formula.

The fourth line causes the method to exit and to pass the value of a to the caller.

The method will not run until we invoke it from main() with a statement like:

Program10b is the complete program. It declares a variable r for the purpose of passing a radius to the area() method, and it declares another variable answer to hold the result. Finally we display the answer to the user.


Compile and execute Program10b.java which uses a method to compute the area of a circle.

Suppose we wish to compute the area of another circle, this time with a radius of 5. Without methods we would have to write the formula in Java again. The beauty of methods is that we can call the same method many times:

Let’s modify our program to calculate more areas.

Compile and execute Program10c.java which calculates the area of three different circles.

This works. But, you can probably see a trend here and realize this is a good place to use a for loop. We can refactor (rewrite and improve) the program as shown below:

The output is the same as Program10c, but the program is more elegant and easier to modify for other values of r.

More Than One Method in a Program

If desired, a program can declare several methods. Here’s a program which has the area() method described above and a new method to compute the circumference of a circle.

Compile and execute Program10e.java which uses two methods to compute the area and circumference of three circles.

Example Method to Draw a Rectangle

Our last example in this section is to write a program that asks the user for the size of a rectangle to draw on the console. The size is determined by two variables, height and width. The rectangle is drawn with a series of asterisk “*” characters in the method DrawRectangle() which takes two arguments, the height and width. Comments in the method describe the four steps needed to display the rectangle.

There is nothing new in Program10f.java that we haven’t seen before, but it is our longest program so far. The program will seem less daunting if you look at it as a series of small chunks of code. Whitespace (blank lines) surround each chunk for readability.

Compile and execute Program10f.java which displays a rectangle with a width and height specified by the user.

 

Overloaded Methods

What if you need to define a method which can return more than one type of result, such as an int result and a double result? You can overload the method by declaring more than one method with the same name and giving each method a different parameter list and return type, as shown here:

The Java compiler determines which method to call based upon how you call the method. If you call the method with two ints, the first method is called. If you call the method with two doubles, the second method is called.

Summary

In this lesson we learned how to use the predefined methods that Java provides, and to create and use static methods of our own design in Java programs. Methods offer a powerful means for accomplishing a very basic task in programming – the process of using the same set of instructions repeatedly.

Next Lesson

Methods are common in Classes, and that’s the subject of our next tutorial on Objects and Classes.

 

2 COMMENTS

  1. […] in a class, you need to declare methods which act upon the instance variables. As we learned in the previous lesson, methods are declared with a statement of the […]

Leave a Reply