Skip to content Skip to navigation

OpenStax-CNX

You are here: Home » Content » Jb0130: Java OOP: A Gentle Introduction to Methods in Java

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Jb0130: Java OOP: A Gentle Introduction to Methods in Java

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: This module provides a gentle introduction to Java methods.

Preface

General

This module is part of a sub-collection of modules designed to help you learn to program computers.

It provides a gentle introduction to Java programming methods.

Prerequisites

In addition to an Internet connection and a browser, you will need the following tools (as a minimum) to work through the exercises in these modules:

The minimum prerequisites for understanding the material in these modules include:

  • An understanding of algebra.
  • An understanding of all of the material covered in the earlier modules in this collection.

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

Discussion and sample code

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 back 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 it 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 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 .

Standard methods

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

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

Passing parameters

Make the method general

Normally, when 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 .

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

Pass me the number please

When your program calls the square-root method, it will need to tell the method the value 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

  • perform an action
  • send back an answer. or
  • some combination of the two

Performing an action

An example of a method that performs an action is the method named println . We used the println method in an earlier module 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

Methods 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 possible. I will have more to say about writing your own methods in future modules.

Sample program

A complete listing of a sample program named SqRt01.java is provided in Listing 5 near the end of the lesson. A batch file that you can use to compile and run the program is provided in Listing 6 .

When you compile and run the program, the following output should appear on your computer screen:

5.049752469181039

6.0

As you will see shortly, these are the square root values respectively for 25.5 and 36.

Interesting code fragments

I will explain portions of this program in fragments. I will explain only those portions of the program that are germane to this module. Don't worry about the other details of the program. You will learn about those details in future modules.

You may find it useful to open this lesson in another browser window so that you can easily scroll back and forth among the fragments while reading the discussion.

The first code fragment that I will explain is shown in Listing 1 .

1
Listing 1: The price of beans.

    double beans;
    beans = 25.5;

What is the price of beans?

The code 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 module. I will discuss them in more detail in a future module.)

What is that double thing?

In an earlier module, I declared a variable with a type named int . At that time, I explained that only integer values could be stored in that variable.

The variable named beans in Listing 1 is declared to be of the type double . I will explain the concept of data types in detail in a future module. Briefly, double means that you can store any numeric value in this variable, with or without a decimal part. In other words, you can store a value of 3 or a value of 3.33 in this variable, whereas a variable with a declared type of int won't accept a value of 3.33.

Every method has a name

Every method, every variable, and some other things as well have names. The names are case sensitive . By case sensitive, I mean that the method named amethod is not the same as the method named aMethod .

A few words about names in Java

There are several rules that define the format of allowable names in Java. You can dig into this in more detail on the web if you like, but if you follow these two rules, you will be okay:

  • Use only letters and numbers in Java names.
  • Always make the first character a letter.

A standard method named sqrt

Java provides a Math library that contains many standard methods. Included in those methods is a method named sqrt that will calculate and return the square root of a number that is passed as a parameter when the method is called.

The sqrt method is called on the right-hand side of the equal sign (=) in the code fragment in Listing 2 .

2
Listing 2: Compute the square root of the price of beans.

    double sqRtBns = Math.sqrt(beans);

Calling the sqrt method

I'm not sure why you would want to do this, but the code fragment in Listing 2

  • calls the sqrt method and
  • passes a copy of the value stored in the beans variable as a parameter.

The sqrt method calculates and returns the square root of the number that it receives as its incoming parameter. In this case, it returns the square root of the price of a can of beans.

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 later in the program. I declared another variable named sqRtBns in the code fragment in Listing 2 . I also caused the value returned from the sqrt method to be stored in, or assigned to, this new variable named sqRtBns .

How should we interpret this code 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 (=) near the center of the line of code. (Later we 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 calls the sqrt method, passing a copy of the value stored in the beans variable to the method.

When the sqrt 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 in the fragment in Listing 3 causes the value now stored in sqRtBns to be displayed on the computer screen.

3
Listing 3: Display the square root value.

    System.out.println(sqRtBns);

Another method is called here

The display of the square root value is accomplished by

  • calling another standard 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 to it as a parameter.

The behavior of the println method is to cause its incoming parameter to be displayed on the computer screen.

What do we mean by syntax?

Syntax is a word that is often used in computer programming. The thesaurus in the editor that I am using to type this document says that a synonym for syntax is grammar.

I also like to think of syntax as meaning something very similar to format.

Syntax for passing parameters

Note the syntax in Listing 2 and Listing 3 for passing a parameter to the method. The syntax consists of following the name of the method with a pair of matching parentheses that contain the parameter. If more than one parameter is being passed, they are all included within the parentheses and separated by commas. Usually, the order of the parameters is important if more than one parameter is being passed.

Reusing the methods

The purpose of the code fragment in Listing 4 is to illustrate the reusable nature of methods.

4
Listing 4: Calling the same methods again.

    double peas;
    peas = 36.;
    double sqRtPeas = Math.sqrt(peas);
    System.out.println(sqRtPeas); 

The code in this fragment calls the same sqrt method that was called before. In this case, the method is called to calculate the square root of the value stored in the variable named peas instead of the value stored in the variable named beans .

This fragment saves the value returned from the sqrt method in a new variable named sqRtPeas . Then the fragment calls the same println method as before to display the value now stored in the variable named sqRtPeas .

Write once and use over and over

Methods make it possible to write some code once and then use that code many times in the same program. 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 a program.

Run the program

I encourage you to run the program that I presented in this lesson to confirm that you get the same results. 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.

Complete program listings

Listing 5 is a complete listing of the program named SqRt01 .

5
Listing 5: The program named SqRt01.

//File SqRt01.java
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

Listing 6 contains the commands for a batch file that can be used to compile and run the program named SqRt01 .

6
Listing 6: A batch file for compiling and running the program named SqRt01.

echo off
cls

del *.class

javac -cp .; SqRt01.java
java -cp .; SqRt01

pause

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Jb0130: Java OOP: A Gentle Introduction to Methods in Java
  • File: Jb0130.htm
  • Published: 12/16/12
  • Revised: 01/02/13

Note:

Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

-end-

Content actions

Download module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks