Java Basics

Methods 1 - Introduction to methods

Purpose of this lesson: New Java language features

Basic idea - A named group of statements - Verbs

By now you have used a lot of the predefined library methods, and written many main methods. This chapter explains methods in more detail.

Java statements are grouped together in methods. Each method must be inside a class. Every method has a name, which starts with a lowercase character and typically is a verb because it does something.

Other terms: The idea of method is in every programming language, but different terms are used in many languages. You might have seen terms like function, procedure, or subroutine. We'll use method consistently here, but you will hear programmers using these equivalent terms occasionally.

Business analogy - services provided by an organization

You could think of classes as corresponding to departments in an organization, and methods as being the services they provide. Let's take an example of calling the telephone information service to get someone's phone number. When you make the call, you pass information, the name of the person whose number you want, to the method (information service). This called "method" then does something, and returns a value to you (the desired phone number). Just as you don't have to know how the information service performs its job, you typically don't need to know exactly how a method does its work, unless of course, you are writing it.

Hierarchical organization. Computer programs are structured in many ways like an organization -- higher levels rely on others to do much of the work. They "call" on lower levels to do the work, passing them all necessary "arguments". In a similar way, the top level of a computer program, main, often consists largely of method calls, and those methods may in turn call on yet other methods.

Terms: call and return

Call. When a method call is encountered in a program, the program remembers where it was and execution goes to the method (calls the method). After a small amount of initialization, the statements in the method are executed starting at the beginning.

Return. When the end of the method is reached or a return statement is executed, the method returns to the where it was called from, and execution continues in the calling method from that point. A method may return a value (eg, parseDouble) or not (showMessageDialog). The call-return terminology is almost universal.

Static (class) methods

Static. This starts with static (also called class) methods because all applications start with the static method main, and many of the early library methods that you use are static methods. Static methods are different than instance methods because they don't have an extra object passed to them.

Instance methods are associated with an object (an "instance" of a class).

Identifying methods

Parentheses follow name. You can identify a method name because it is always followed by left and right parentheses, which may enclose arguments (parameters). If you see a left parenthesis with a name preceding it, it will be a method call or definition, or a constructor (constructors are very similar to methods). In the following example each method name is highlighted.

When calling methods outside of the current class, eg, in the Java library, static methods are preceded by the class name (followed by a dot), and instance methods are preceded by an object. When a static method is defined, the keyword "static" will preceded it. The example below has only static methods.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
 25 
 26 
 27 
 28 
 29 
 30 
// File   : methods/KmToMiles.java
// Purpose: Convert kilometers to miles. Use JOptionPane for input / output.
// Author : Fred Swartz
// Date   : 22 Apr 2006

import javax.swing.*;

public class KmToMiles {
    //============================================================ constants
    private static final double MILES_PER_KILOMETER = 0.621;    

    //================================================================= main
    public static void main(String[] args) {                        //Note 1
        //... Local variables
        String kmStr;    // String km before conversion to double.
        double km;       // Number of kilometers.
        double mi;       // Number of miles.

        //... Input
        kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
        km = Double.parseDouble(kmStr);

        //... Computation
        mi = km * MILES_PER_KILOMETER;

        //... Output
        JOptionPane.showMessageDialog(null, km + " kilometers is "
                                          + mi + " miles.");
    }
}

Notes

  1. This defines a method called "main". Everything between the "{" on the end of this line to the matching "}" second from the end is the "body" of the method.

The above code defines the static main method, which someone (eg, the operating system) will call with KmToMiles.main(. . .).

To do its work, main calls on other methods: showInputDialog, which is defined in the JOptionPane class, parseDouble, which is defined in the Double class, and showMessageDialog, which is also in the JOptionPane class.

Whenever you call a static method in a different class, precede it with the name of the class containing its definition, followed by a dot. If you don't specify the class name, it assumes the method is defined in the current class.

Identifying instance methods

Object precedes. Instance method calls are identified in the following program. Note that they are all preceded by an object reference. This object is used by the methods to do their work. In this case, the objects are strings.

In addition to supplying the object's data to the method, the class of the object, eg String, is where the method is defined.

  1 
  2 
  3 
  4 
  5 
  6 
  7 
  8 
  9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
// File   : dialog/capitalize/Capitalize2.java
// Purpose: Capitalize first letter of each name.  Declare with first use.
// Author : Fred Swartz - placed in public domain.
// Date   : 30 Mar 2006

import javax.swing.*;

public class Capitalize2 {

    public static void main(String[] args) {
        //.. Input a word
        String inputWord = JOptionPane.showInputDialog(null, "Enter a word");

        //.. Process - Separate word into parts, change case, put together.
        String firstLetter = inputWord.substring(0,1);  // Get first letter
        String remainder   = inputWord.substring(1);    // Get remainder of word.
        String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase();

        //.. Output the result.
        JOptionPane.showMessageDialog(null, capitalized);
    }
}

Review Questions

[TODO] - show sample code, ask to identify methods and the classes they are defined in.