Computer Programming for Homeschool Students and Other Beginners

Programming Fundamentals using Java

Introduction to Methods

Learn why methods are useful.  Also learn how to use a method from the Java Math library along with a method that is used to display information on the computer screen.

Published:  May 31, 2008
By Richard G. Baldwin

Homeschool Programming Notes # 304


 

Preface

General

This tutorial lesson is part of a continuing series that is designed specifically for teaching computer programming to homeschool students and their parents.  Even though the series is designed for homeschool students, everyone is welcome to use the lessons to learn computer programming.

In this lesson, I will explain why methods are useful.  I will also show you how to use a method from the Java Math library along with a method that is used to display information on the computer screen.

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the listings while you are reading about them.

Listings

Supplementary material

I recommend that you also study the other lessons in my extensive collection of online programming tutorials.  You will find a consolidated index at www.DickBaldwin.com.

Introduction

Methods have been used in computer programming since the early days of programming.  Methods are often called functions, procedures, subroutines, and various other names.

Calculate the square root

Suppose that your program needs to calculate the square root of a number.  Referring to your high-school algebra book, you could refresh your memory on how to calculate a square root.  Then you could construct the algorithm describing that process.  Having the algorithm available, you could write the code to calculate the square root and insert that code into your program code.  Then you could compile, and run your program.  If you did it all correctly, your program should calculate the square root.  (For reasons that will become apparent later, I will refer to the code that you inserted as in-line code.)

Oops, need to do it all over again

Suppose that further on in your program you discover that you need to calculate the square root of another number.  And later, you discover that you need to calculate the square root of still another number.  Obviously, with a few changes, you could copy your original code and insert it as in-line code at each location in your program where you need to calculate the square root of a number.

Is there a better way?

However, after doing this a few times, you might start asking if there is a better way.  The answer is "yes, there is a better way."

A method provides a better way

The better way is to create a separate program module that has the ability to calculate the square root and to make that module available for use as a helper to your main program each time your main program needs to calculate a square root.  In Java, this separate program module is called a method.

Library Methods

The Java programming language contains a large number of prewritten methods (in the class libraries) that are already available for your use.  (Later, I will illustrate the use of a library method for calculating the square root of a number.)

In addition to the library methods that are already available, if you need a method to perform some operation and there is no library method already available to perform that operation, you can write your own method.

Passing Parameters

Make the method general

Normally, in the case of designing and writing a method such as one that can calculate the square root of a number, it is desirable to write it in such a way that it can calculate the square root of any number (as opposed to only one specific number).  This is accomplished through the use of something called parameters.

Pass me the number please

The process of causing a method to be executed is commonly referred to as calling or invoking the method.

When your program calls the square-root method, it will need to tell the method the value of the number for which the square root is needed.  In general, many methods will require that you provide certain kinds of information when you call them.  The code in the method needs this information to be able to accomplish its purpose.

Passing parameters

This process of providing information to a method when you call it is commonly referred to as passing parameters to the method.  For the square-root method, you need to pass a parameter whose value is the value of the number for which you need the square root.

Returning Values

A method will usually Performing an action

An example of a method that performs an action is the method named println.  We have used the println method several times to cause information to be displayed on the computer screen.  This method does not need to send back an answer, because that is not the objective of the method.  The objective is simply to display some information.

Sending back an answer

On the other hand, a method that is designed to calculate the square root of a number needs to be able to send the square-root value back to the program that called the method.  After all, it wouldn't be very useful if the method calculated the square root and then kept it a secret.  The process of sending back an answer is commonly referred to as returning a value.

Returned values can be ignored

When methods are designed, they can be designed in such a way that they either will or will not return a value.

When a method does return a value, the program that called the method can either pay attention to that value and use it for some purpose, or ignore it entirely.  For example, in some cases where a method performs an action and also returns a value, the calling program may elect to ignore the returned value.

On the other hand, if the sole purpose of a method is to return a value, it wouldn't make much sense for a program to call that method and then ignore the value that is returned (although that would be technically possible).

Writing Your Own Methods

As mentioned earlier, you can write your own methods in Java.  I mention this here so you will know that it is a possibility.  I will have more to say about writing your own methods in future lessons.

Sample Program

A complete listing of this sample program is provided in Listing 5 near the end of this lesson.  You should be able to copy it into a source file named SqRt01.java and then compile and execute it.  When you do, the following output should appear on your computer screen:

5.049752469181039
6.0

As you will see when we examine the program, these are the square root values respectively for 25.5 and 36.

Interesting Code Fragments

I am going to discuss this program in fragments.  I will discuss only those portions of the program that are germane to this lesson.  Don't worry about the other details of the program.  You will learn about those details in future lessons.

What is the price of beans?

The first fragment shown in Listing 1 declares a variable named beans and assigns a value of 25.5 to the variable.  (I briefly discussed the declaration of variables in a previous lesson.  I will discuss them in more detail in future lessons.)

Listing 1. Declaration of a variable named beans.
    double beans;
    beans = 25.5;

What is that double thing?

The variable named beans is declared to be of the type double.  For now, don't worry about exactly what this means.  I will discuss the concept of type in detail in a future lesson.  Suffice it to say at this point that the double type makes it possible for you to store values that have a fractional part in memory.

Every method has a name

Every method has a name, and the name is case sensitive.  As you learned in the section on variable names in the previous lesson, the method named amethod is not the same as the method named aMethod.

A library method named sqrt

Java provides a Math library that makes many methods available for computing common mathematical functions.  Included in those methods is one that can be used to calculate and return the square root of a positive number that is passed as a parameter to the method when it is called.  The sqrt method is called on the right-hand side of the equal sign (assignment operator) in the code fragment shown in Listing 2.

Listing 2. Calling the library sqrt method.
    double sqRtBns = Math.sqrt(beans);

Using the sqrt method

The fragment in Listing 2 calls the sqrt method and passes a copy of the value stored in the variable named beans as a parameter.  The sqrt method calculates and returns the square root of the number that it receives as its incoming parameter.

A place to save the square root

I needed some place to save the square root value until I could display it on the computer screen, so I declared another variable for that purpose in the code fragment in Listing 2.  This new variable is named sqRtBns.  I caused the value returned from the sqrt method to be stored in (assigned to) this new variable.

How should I interpret the above fragment?

You can think of the process implemented by the code fragment in Listing 2 as follows.

First note that there is an equal sign (=) in the center of the statement.  (Later you will learn that this is called the assignment operator.)

The code on the left-hand side of the assignment operator causes a new chunk of memory to be set aside and named sqRtBns(We call this chunk of code a variable.)

The code on the right-hand side of the assignment operator causes the sqrt method to be executed, passing a copy of the value stored in the beans variable to the method.

When the method returns the value that is the square root of its incoming parameter, the assignment operator causes that value to be stored and saved in the variable named sqRtBns.

Now display the square root value

The code fragment in Listing 3 causes the value now stored in sqRtBns to be displayed on the computer screen.

Listing 3. Display the square root value.
    System.out.println(sqRtBns);

Another method is called here

This is accomplished by calling another library method named println and passing a copy of the value stored in sqRtBns as a parameter to the method.  The println method performs an action (displaying something on the computer screen) and doesn't return a value.

A method exhibits behavior

We say that a method exhibits behavior. The behavior of the sqrt method is to calculate and return the square root of the value passed into it as a parameter.  The behavior of the println method is to cause its incoming parameter to be displayed on the computer screen.

Syntax for passing parameters

Note the syntax in both Listing 2 and Listing 3 for passing a parameter to the method.  The syntax always consists of a pair of matching parentheses that contain the parameter.  The matching parentheses follow the name of the method.  If there is more than one parameter required, they are included within the parentheses and separated by commas.

Reusing the methods

The purpose of the fragment in Listing 4 is to illustrate the reusable nature of methods.  This fragment uses the same sqrt method that was used before to calculate the square root of the value stored in another variable named peas.

Listing 4. Reusing the methods.
    double peas;
    peas = 36.;
    double sqRtPeas = Math.sqrt(peas);
    System.out.println(sqRtPeas); 

Listing 4 saves the result in a new variable named sqRtPeas.  Then it uses the same println method as before to display the value now stored in the variable named sqRtPeas on the computer screen.

Write once and use over and over again

Therefore, methods make it possible to write some code once and then use that code many times in the same or different programs.  This is the opposite of in-line code, which requires you to write essentially the same code multiple times in order to accomplish the same purpose more than once in the program.

Run the program

I encourage you to copy the code from Listing 5 into your source-code editor.  Compile the code, and execute it.  Experiment with the code, making changes, and observing the results of your changes.  Make certain that you can explain why your changes behave as they do.

Student programming project

In addition to the sqrt method, the Java Math library provides a method named cos that receives an incoming angle in radians and returns the cosine of that angle.  In addition, the Math library provides a method named toRadians that receives an incoming angle in degrees and returns the angle in radians.

Write a Java program that computes and displays the cosine of 45 degrees.  The correct answer is:

0.7071067811865476

Summary

In this lesson, I explained why methods are useful.  I also showed you how to use a method from the Java Math library along with a method that is used to display information on the computer screen.

What's next?

In the next few lessons, we will deal with comments and types and will provide more in-depth coverage of variables and literals.

Resources

General resources

Previous lessons in the series

Complete program listing

A complete listing of the program presented in this lesson is shown in Listing 5.

Listing 5. Complete listing of the program named SqRt01.
class SqRt01{ 
  public static void main(String[] args){
    double beans;
    beans = 25.5;
    double sqRtBns = Math.sqrt(beans);
    System.out.println(sqRtBns);
    double peas;
    peas = 36.;
    double sqRtPeas = Math.sqrt(peas);
    System.out.println(sqRtPeas); 
  }//end main 
}//End SqRt01 class

 


Copyright

Copyright 2008, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java, C#, and XML. In addition to the many platform and/or language independent benefits of Java and C# applications, he believes that a combination of Java, C#, and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.

In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP).  His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments.  (TI is still a world leader in DSP.)  In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

Baldwin@DickBaldwin.com

-end-