What You Will Learn
  • Review void methods
  • Review non-void methods
  • Review formal parameters
  • Review actual parameters
  • Review local variables

Anatomy of a Class

Recall that Java classes are made up of two main sections: variable declaration section and method declaration section. The variable declaration section defines an object's data requirements (instance variables) and the method declaration section defines an object's behavior in response to messages. Both variables and methods are members of the class. The combining of data and behavior into a single package (i.e. class) is called encapsulation.

The code below defines a class named Die that represents a six-sided die. Notice the variable declaration section is at the beginning of the class and the method declaration section is at the end. The ordering of the two sections does not matter. Most programmers prefer to locate the variables section at the beginning of the class.

public class Die
{
    
// variable declarations (instance variables)
private int faceValue;
// method declarations
public void roll() { faceValue = (int)(Math.random() * 6) + 1; } public int getFaceValue() { return faceValue; } }

Methods

A method is a group of programming language statements that is given a name. Every method in a Java program must be defined within a particular class. To create a method you must have a method declaration which consists of two parts: a method header and a method body. Here are two method declarations, roll and getFaceValue, defined in the Die class.

// method declarations
public void 
roll
() { faceValue = (int)(Math.random() * 6) + 1; } public int
getFaceValue
() { return faceValue; }

When a method is invoked(called), the statements of that method are executed. When that method is done, control returns to the location where the call was made and execution continues.

A method that is called might be part of the same class as the method that called it, or it might be part of a different class. If the called method is part of the same class, only the method name is needed to call it.

doSomething();

If the method is a member of a different class, it is invoked through an object created by that class. The call is made using dot notation which includes the object name, followed by a dot, and ending with the method name.

myClass myObject = new myClass();   // instantiate object
myObject.doSomething();

Method Header

The method header, which appears at the beginning of a method definition, lists several important things about the method, including the method's name, an access modifier, the type of the return value, and a list of parameters that the method accepts. The method body is a collection of statements that are performed when the method is executed. The body is defined in a block inside braces.

Access Modifiers

The access to classes, constructors, methods and fields(instance variables) are regulated using access modifiers. These modifiers allow a class control over what information and methods can be accessible by other classes.

Java provides four access modifiers to help you set the level of access you want for the fields, methods, and constructors in your classes. The four access modifiers are

public access modifier

Methods declared public within a class are visible to any class in the Java program, whether these classes are in the same package or in another package. This means that any variable or method declared public can be accessed freely by any other class.

private access modifier

Methods declared private are strictly controlled, which means they cannot be accessed outside the enclosing class.

protected access modifier

Methods declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member's class. (The protected access modifier is not currently part of AP Java subset and therefore will not be tested on the AP exam.)

default access modifier

Java provides a default specifier which is used when no access modifier is present. Any method that has no declared access modifier is accessible only by classes in the same package.

A Java package is a set of classes which are grouped together. To use a class contained within a package, you must either import the package or use the fully qualified class name each time you use the class.

import java.util.Scanner;  // imported Scanner class from java.util package 

Scanner keyboard = new Scanner(System.in);
int num = keyboard.nextInt();

or

// did not import Scanner class therefore must use the
// fully qualified class name each time Scanner class is referenced

java.util.Scanner keyboard = new java.util.Scanner(System.in);
int num = keyboard.nextInt();

The return statement

The return type in the method header can be a primitive type, class name, or the reserved word void. When a method does not return any value, void is used as the return type, as is always done with the main method. The roll method is an example of a method void of a return value

public void roll()
{
   faceValue = (int)(Math.random() * 6) + 1;
}

This type of method is often referred to as a void method.

A method that returns a value must have a return statement. After a return statement is executed, control is immediately returned to the statement in the calling method, and processing continues there. A return statement is the reserved word return followed by an expression that dictates the value to be returned. The value returned by the method is often a calculation performed by the method. The value returned must match the return type specified in the method header.

The getFaceValue method is an example of a method that has a return value

public int getFaceValue()
{
   return faceValue;       // faceValue is of type int
}

A method that does not return a value does not usually need a return statement because it automatically returns to the calling method when it is done. A method with a void return type may, however, have a return statement without an expression.

public void myMethod(int num)
{
   if(num < 0)
     return;         // method is terminated, but it does not return anything
   else
     < do something >
}

Invoking void Methods

A void method is invoked from another method by making a reference to its name followed by its parameter list.

public void roll()
{
   faceValue = (int)(Math.random() * 6) + 1;
}

public void anotherMethod()
{
    roll();    // method call
}

Invoking non-void Methods (Functions)

When invoking a non-void method (a method that returns a value) it is called from within another statement. Look at the following example.

public int getFaceValue()
{
   return faceValue;       // faceValue is of type int
}

public void anotherMethod()
{
    int value = getFaceValue();  // getFaceValue is called from within
                                 // an assignment statement(=)
}

Since the method getFaceValue is returning a value, the calling method anotherMethod needs to do something with the value that is being returned. In this example, it is storing the return value in a variable named value. Look at another example.

public int getFaceValue()
{
   return faceValue;       // faceValue is of type int
}

public void anotherMethod()
{
    System.out.println(getFaceValue()); // getFaceValue is called from
                                        // within a println statement
}

In this example, the call to the method getFaceValue is embedded in a println statement. When the getFaceValue method is called its return value is passed on to the println method which then becomes an actual parameter for the println method. Let's look at one more example.

public int getFaceValue()
{
   return faceValue;       // faceValue is of type int
}

public void anotherMethod()
{
    if(getFaceValue() > 6)  // getFaceValue is called from within an if statement
    {
	    System.out.println("invalid number");
    }
}

In this example, the call to the getFaceValue method is embedded in an if statement. The if statement uses the return value of the method as the first operand of its boolean expression.


Parameters

A parameter is a value that is passed into a method when it is invoked.

The parameters in the header of the method declaration are called formal parameters. The values passed into a method are called actual parameters or arguments. The parameter list is always in parentheses after the method name. If there are no parameters, the parentheses are empty.

The formal parameters are identifiers that act as variables inside the method. Their initial values come from the actual parameters in the invocation. When a method is called, the value in each actual parameter is copied and stored in the matching formal parameter. In the example above, the actual parameter value 5 is copied into the formal parameter count. Giving the variable count an initial value of 5.

The actual parameter can be a literal value, like the value 5 above, or it can be a variable. Look at the following example.

public void instructions(int count)
{
    System.out.println("Follow all instructions.");
    System.out.println("Use not more than " + count + " turns.");
}

public void anotherMethod()
{
    int numTurns = 7;
    instructions(numTurns);
}

The variable numTurns is the actual parameter. It contains a value of 7 which is copied into the formal parameter count when the instructions method is called.

Actual parameters can be expressions. If an expression is used as an actual parameter, it is fully evaluated before the method call and the result is passed the parameter. Look at the following example.

public void instructions(int count)
{
    System.out.println("Follow all instructions.");
    System.out.println("Use not more than " + count + " turns.");
}

public void anotherMethod()
{
    instructions(20/5 + 2*3);
}

In this example the actual parameter is the expression 20/5 + 2 * 3. When the instructions method is called the expression is evaluated to a value of 10. The value 10 becomes the actual parameter which is then copied into the formal parameter count.

A method can have an number of formal parameters in its parameter lists. Each parameter must be separated by a comma. Look at the method below that declares four parameters representing three six weeks averages and a semester exam.

public double calculateSemesterAvg(int s1, int s2, int s3, int exam)
{
    return (s1 + s2 + s3) * .8 + exam * .2;
}

The method can be invoked using actual parameters like the following code

double semesterAvg = calculateSemesterAvg(80, 90, 95, 88);

or with actual parameters that are variables

double semesterAvg = calculateSemesterAvg(sixWeeks1, sixWeeks2, sixWeeks3, exam);

If the method calculateSemesterAvg belongs to another class named myObject the method invocation would look like the following

double semesterAvg = myObject.calculateSemesterAvg(80, 90, 95, 88);

or

double semesterAvg = myObject.calculateSemesterAvg(sixWeeks1, sixWeeks2, sixWeeks3, exam);

The parameter list in the invocation and the method declaration must match up. That is, the value of the first actual parameter is copied into the first formal parameter, the second actual parameter into the second formal parameter, and so on. The types of the actual parameter must match the types of the formal parameters.


Local Data

Recall that the scope of a variable (or constant) is the part of a program where a valid reference to that variable can be made. A variable can be declared inside a method, making it local data as opposed to instance data. An instance variable is declared in a class but not inside any particular method. A local variable has scope limited to only the method where it is declared. A local variable simply does not exist outside of the method in which it is declared. Instance data, declared at the class level, has a scope of the entire class; any method of the class can refer to it.

public void myMethod()
{
   int num = 0;    // local variable

   < do something >
}

The formal parameter names in a method header serve as local data for that method. They don't exist until the method is called, and they stop existing when the method ends.

public void myMethod(double size)   // size is created here, 
{                                   // its value comes from the actual parameter
   < do something >
}   
// size no longer exists, it was only a temporary (local) variable