ITEC 120
L05a: Methods

Part I – Mechanics

This is a two-part lab. Part I reviews the mechanics of creating, calling, and working with methods. Part II applies what you have learned about the mechanics to solve problems with methods. You are encouraged to work with a partner on all labs, especially this one. Answer the questions below shown in green.

Part I Objective

To successfully complete this portion of the lab, you will call methods, pass values to methods, and return values from methods. You will also know what a stub method is and you will identify the distinguishing parts of a method signature.

Mechanics

Create a workspace for the lab and change into the L05a directory.

mkdir L05a
cd L05a

Create a driver class named Drv and create a service class named Srv. The driver class will call methods in the service class. The driver class has exactly one method named main. Create the main method but do not write any code in the main method. Compile both classes to verify there are no errors.

The Random class and the Scanner class are both service classes. You have written programs (drivers) that use the Random and Scanner classes.   Therefore, you have developed programs that use multiple classes but this is the first time you are writing more than one class.

Every class is saved in its own file. Save the Drv class in a file named Drv.java and save the Srv class in a file named Srv.java. It will be helpful to have both files open at the same time. To do this in jEdit, click on the View menu and click on Splitting. If you split your workspace vertically, jEdit will open two files next to each other. If you split your workspace horizontally, one file will be on top of the other.

Create the Drv and Srv classes exactly as shown below. Be sure to include the tabs (\t) in the print statements in the sum method. If you have entered the code correctly, both classes will compile without error.

public class Srv
{
    public void sum()
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tEnding Srv.sum");
    }
}


public class Drv
{
    public static void main(String[] args)
    {
        System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        System.out.println("Calling Srv.sum");
        srvObj.sum();
        System.out.println("\nReturned to driver");
        System.out.println("Ending the driver");
    }
}

Execute the Srv class from the command line. (Compile first.)

     > java Srv

What error do you get when you execute the Srv class?

Execute the Drv class from the command line.

Why are you able to execute the Drv class and you cannot execute the Srv class?

Consider the two lines of code highlighted below. Recall the pattern to call a method:

object.method_name(parameter values);

If you want to call Dominos to order a pizza you need the phone number for Dominos. If you want to call a method in the Srv class you need an object – an instance of the Srv class. The first highlighted line of code creates an instance of the Srv class (an object) and saves the instance in the variable srvObj. As shown in the second highlighted line of code, the driver uses the Srv object (srvObj) to call the sum method in the service class.

public class Drv
{
    public static void main(String[] args)
    {
        System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        System.out.println("Calling Srv.sum");
        srvObj.sum();
        System.out.println("\nReturned to driver");
        System.out.println("Ending the driver");
    }
}

Parameters

The sum method does not yet do anything useful. If we want the method to add two integers the method must receive two inputs (i.e., the two numbers that will be added together). Inputs are passed to a method using parameters. As shown below, add two parameters to the sum method.

public class Srv
{
    public void sum(int num1, int num2)
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tEnding Srv.sum");
    }
}

Consider the sum method above. Notice that the parameters num1 and num2 are declared like any other variable. Each parameter has a data type and a name. If a method has more than one parameter, the parameters are separated by commas.

Compile the service class and then compile the driver class. What error did you get?

What do you think this error means?

Any call to a method with parameters must pass one value for each parameter. Any call to the sum method shown above must pass two integer values.

As shown in the line of code highlighted below, modify the call to the sum method and pass the integers 1 and 2.

public class Drv
{
    public static void main(String[] args)
    {
        System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        System.out.println("Calling Srv.sum(1, 2)");
        srvObj.sum(1, 2);
        System.out.println("\nReturned to driver");
        System.out.println("Ending the driver");
    }
}

Compile both classes to verify there are no errors and run the driver.

What would happen if you passed two doubles to the sum method?

Test your hypothesis by modifying the highlighted line of code above to pass two doubles (1.5, 2.2) to the sum method. Compile and execute the driver class.

Explain what happens when you pass a double value to an integer parameter. Why does this happen?

Change the values in the call to the sum method back to 1 and 2 and compile the driver class.

What would happen if you passed two integers to a method that requires two doubles?

As shown below, modify the sum method in the service class and change both parameters to double.

public void sum(double num1, double num2)

Compile the service class and execute the driver. Explain what happens when you pass an integer value to a double parameter. Why does this happen?

Change the parameters back to int. As shown in the highlighted code below, add a print statement to the sum method to print the value of each parameter.

public class Srv
{
    public void sum(int num1, int num2)
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tnum1: " + num1 +
                           "  num2: " + num2);
        System.out.println("\tEnding Srv.sum");
    }
}

Compile the service class to verify there are no errors. Execute the program. What is the output of the print statement highlighted above?

As shown in the highlighted code below, in the driver class, add a second call to the sum method and pass values 2 and 1.

public class Drv
{
    public static void main(String[] args)
    {
        System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        System.out.println("Calling Srv.sum(1, 2)");
        srvObj.sum(1, 2);
        System.out.println("\nReturned to driver");
        System.out.println("Calling Srv.sum(2, 1)");
        srvObj.sum(2, 1);
        System.out.println("\nReturned to driver");
        System.out.println("Ending the driver");
    }
}

Examine the output from the sum method. What does this tell you about how values are assigned to parameters?

What happens when variables are passed to a method? Modify the driver by adding the code below highlighted in yellow. Compile and execute the driver.

public class Drv
{
    public static void main(String[] args)
    {
        System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        System.out.println("Calling Srv.sum(1, 2)");
        srvObj.sum(1, 2);
        System.out.println("\nReturned to driver");
        System.out.println("Calling Srv.sum(2, 1)");
        srvObj.sum(2, 1);
        System.out.println("\nReturned to driver");
 
        int n1 = 5;
        int n2 = 10;
        System.out.println("Calling sum(" + n1 + ", "
                           + n2 + ")");
        srvObj.sum(n1, n2);
        System.out.println("\nReturned to driver");
       
        System.out.println("Calling sum(" + n2 + ", "
                           + n1 + ")");
        srvObj.sum(n2, n1);
        System.out.println("\nReturned to driver");
        System.out.println("Ending the driver");
    }
}

Add the code above highlighted in green to the driver. Compile and execute the program.

Is there any difference between passing literal values, like 2, and variables?

Method Signatures

A method signature uniquely identifies a method. A method signature consists of the four components shown below.

  visibility

  return type

  method name

  (parameters)

Which of these four components do you think the compiler use to identify a method?

As shown below, in the service class, create a second method named sum. This method is identical to the first sum method except for the visibility.

public class Srv
{
    // sum 1
    public void sum(int num1, int num2)
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tnum1: " + num1 +
                           "  num2: " + num2);
        System.out.println("\tEnding Srv.sum");
    }
 
    // sum 2
    private void sum(int num1, int num2)
    {
    }
}

Compile the service class. What error did you receive?

What does this tell you about the visibility of a method?

As shown below, modify the second sum method to be public and to return a String instead of void.

public class Srv
{
    // sum 1
    public void sum(int num1, int num2)
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tnum1: " + num1 +
                           "  num2: " + num2);
        System.out.println("\tEnding Srv.sum");
    }
 
    // sum 2
    public String sum(int num1, int num2)
    {
    }
}

What error did you receive? What does this tell you about return types?

As shown below, add a return statement to the second sum method.

public class Srv
{
    // sum 1
    public void sum(int num1, int num2)
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tnum1: " + num1 +
                           "  num2: " + num2);
        System.out.println("\tEnding Srv.sum");
    }
 
    // sum 2
    public String sum(int num1, int num2)
    {
        return "Hello";
    }
}

Compile the service class. What error did you receive?

What does this tell you about the return type in a method signature?

Modify the second sum method as shown below. Remove the return statement, change the return type, and change the names of the parameters. The signatures of the first and second sum methods are identical except for the names of the parameters.

public class Srv
{
    // sum 1
    public void sum(int num1, int num2)
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tnum1: " + num1 +
                           "  num2: " + num2);
        System.out.println("\tEnding Srv.sum");
    }
 
    // sum 2
    public void sum(int num2, int num3)
    {
    }
}

Compile the service class. What error did you receive?

What does this tell you about the names of the parameters in a method signature?

As shown below, change the data type of the first parameter from int to String. The signatures of the first and second sum methods are identical except for the data types of the parameters.

public class Srv
{
    // sum 1
    public void sum(int num1, int num2)
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tnum1: " + num1 +
                           "  num2: " + num2);
        System.out.println("\tEnding Srv.sum");
    }
 
    // sum 2
    public void sum(String num1, int num2)
    {
    }
}

Compile the service class to verify there are no errors. What does this tell you about the types of the parameters in the method signature?

Add a third sum method as shown below.

public class Srv
{
    // sum 1
    public void sum(int num1, int num2)
    {
        System.out.println("\n\tStarting Srv.sum");
        System.out.println("\tnum1: " + num1 +
                           "  num2: " + num2);
        System.out.println("\tEnding Srv.sum");
    }
 
   // sum 2
    public void sum(String num1, int num2)
    {
    }
 
    // sum 3
    public void sum(int num, String s)
    {
    }
}

Compile the service class to verify there are no errors. What is the difference between the method signatures for the second and third sum method?

What does this tell you about the order of parameters?

How can you have two methods with the same name?

Returning Values

Modify the both sum methods as shown below.

public class Srv
{
    // sum 1
    public int sum(int num1, int num2)
    {
        //System.out.println("\n\tStarting Srv.sum");
        //System.out.println("\tnum1: " + num1 +
        //                   "  num2: " + num2);
        //System.out.println("\tEnding Srv.sum");
 
        return (num1 + num2);
    }
 
    // sum 2
    public String sum(String s, int num)
    {
        return (s + num);
    }
}

As shown below, extend the driver class by adding a call to the sum method with the String "ITEC" and the number 120.

public class Drv
{
    public static void main(String[] args)
    {
        //System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        srvObj.sum(1, 2);
        srvObj.sum("ITEC", 120);
 
/*****
        System.out.println("Calling Srv.sum(1, 2)");
        srvObj.sum(1, 2);
        System.out.println("\nReturned to driver");
        System.out.println("Calling Srv.sum(2, 1)");
        srvObj.sum(2, 1);
        System.out.println("\nReturned to driver");
 
        int n1 = 5;
        int n2 = 10;
        System.out.println("Calling sum(" + n1 + ", "
                           + n2 + ")");
        //srvObj.sum(n1, n2);
        System.out.println("\nReturned to driver");
       
        System.out.println("Calling sum(" + n2 + ", "
                           + n1 + ")");
        srvObj.sum(n1, n2);
        System.out.println("\nReturned to driver");
        System.out.println("Ending the driver");
*****/
    }
}

The code above highlighted in yellow contains two calls to the sum method. Which sum method(s) is/are being called? How can you tell?

Compile the service class, compile the driver class, and execute the driver. What output does the program produce? Why?

Notice that both methods have a return statement. The first sum method returns an integer and the second sum method returns a String. What is happening to the values returned by the sum methods?

What can you do to capture the values returned by the methods?

Modify the driver as shown below. Do not change the code that is commented out.

public class Drv
{
    public static void main(String[] args)
    {
        //System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        String str = srvObj.sum(1, 2);
        srvObj.sum("ITEC", 120);
 /*****
*****/
    }
}

Compile the driver class. What error did you receive? Why?

How can you fix this error?

As shown below, an assignment statement has a left hand side (LHS) and a right hand side (RHS). The RHS always evaluates to a value. The value produced by the RHS is assigned to the variable on the LHS. The data type of the value on the RHS must match the data type of the variable on the LHS.

LHS = RHS;

int num = srvObj.sum(1, 2);

When the RHS is a call to a method, the return type of the method must match the data type of the variable on the LHS. The compiler uses the return type in the method signature to check that the data type of the RHS will match the data type of the variable.

Modify the driver class as shown below. Do not change the code that is commented out.

public class Drv
{
    public static void main(String[] args)
    {
        //System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        int result = srvObj.sum(1, 2);
        System.out.println("1 + 2 = " + result);
        srvObj.sum("ITEC", 120);
    }
}

Compile and execute the driver class. What output does the program produce? Why?

Modify the driver class as shown below. Do not change the code that is commented out.

public class Drv
{
    public static void main(String[] args)
    {
        //System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        int result = srvObj.sum(1, 2);
        System.out.println("1 + 2 = " + result);
        int num = srvObj.sum("ITEC", 120);
        System.out.println("ITEC + 120 = " + str);
    }
}

Compile the driver class. What error did you receive? Why?

How can you fix this error?

Modify the driver class as shown below. Do not change the code that is commented out.

public class Drv
{
    public static void main(String[] args)
    {
        //System.out.println("\nStarting the driver");
        Srv srvObj = new Srv();
        int result = srvObj.sum(1, 2);
        System.out.println("1 + 2 = " + result);
        String str = srvObj.sum("ITEC", 120);
        System.out.println("ITEC + 120 = " + str);
    }
}

Compile and execute the driver class. What output does the program produce? Why?

If you call a method that returns a value, is the caller required to store the value that is returned?

When calling a method that returns a value, what must the caller do to capture the value returned by the method?

The labs you have completed thus far have shown you how to learn by testing. In this lab you tried many things to learn what works, what doesn't work, and why. As you progress in your academic and professional careers you will be expected to learn what you need to know to achieve results. The ability to learn by testing is a highly valuable skill.

After completing this portion of the lab, you should understand how to develop a program with two classes: a driver class and a service class. You should know how to run a program with two classes. You should know how to call a method in a service class from a driver class. You should know how to pass input values to a method. You should know which components of a method signature are used to identify a method. You should also know when a method requires a return statement and you should know how to capture the value returned by a method.

Part II – Problem Solving

In this section of the lab you will apply the mechanics you learned in Part I to write methods that solve problems.

Part II Objective

To successfully complete this lab, you will create and use driver classes and create and use methods.

Assignment

You will create several methods in a service class named Geometry and you will create several driver classes that use the methods in the Geometry class. Recall that a driver is a class with exactly one method, the main method. 

Think of the Geome­try class as a cookbook that contains many recipes. It is helpful to collect all of your recipes into one book. Each driver class is similar to a meal. Each meal will include different dishes just as each driver class will use different methods. Each time you create a dish you reuse one of the recipes – you do not rewrite the recipe before you use it. Similarly, when you write and test a method you reuse the method whenever you need it, you do not rewrite the method.

Geometry

Create a service class named Geometry in a file named Geometry.java. This is the last time you will be given the name of the file. You should know that the name of a Java file must match the name of the class with the exact same capitalization.

Create a header comment at the top of your file that includes a description of the class, the names of the authors, and today's date. The description for the Geome­try class is, "contains geometry methods."

Area

In the Geometry class, create a method named area that takes two integer parameters: the height and width of a rectangle, and returns the area of the rectangle.

GeomTest Driver

Create a driver class named GeomTest. This class will test the methods in the Geometry class. Import the Scanner class, create the main method, declare two integer variables named height and width, and prompt the user to enter the height and width of a rectangle. Compile and execute your class before proceeding.

As shown below, create an instance of the Geometry class, call the area method with the height and width, and print the result.

Geometry geomObj = new Geometry();

double recArea = geomObj.area(height, width);
System.out.println("The area of a rectangle with height "
                 + height + " and width " + width
                 + " is " + recArea);

Testing

What values should we test? As shown below, start with a rectangle and a square. Next, it's always a good idea to test 0. Finally, test negative values. When all 8 test cases pass

  1. area(2, 3) --> 6
  2. area(2, 2) --> 4
  3. area(0, 0) --> 0
  4. area(5, 0) --> 0
  5. area(0, 7) --> 0
  6. area(-3, -2) --> 6
  7. area(-2, 4) --> -8
  8. area(5, -3) --> -15

Perimeter

In the Geometry class, create a method named perimeter that takes two integer parameters: the height and width of a rectangle, and returns the perimeter of the rectangle.

Perimeter Driver

Create a class named PerimeterDriver. Prompt the user to enter the height and width of a rectangle, calculate the perimeter, and print the result.

Challenge Problems

Optional

Volume

The volume of a container, such as a box, may be calculated by multiplying the length, height, and width of the sides. In the Geometry class, create a method named volume that takes three integer parameters: the length, height and width of a rectangle, and returns the volume.

Volume Driver

Create a class named VolumeDriver. Prompt the user to enter the length, height, and width of a container, calculate the volume, and print the results.

Density

The density of an object is calculated by dividing the mass (we will use weight), of the object by its volume (mass / volume). In the Geometry class, create a method named density that takes four integer parameters: mass, length, height and width of an object, and returns the density. The density method should use the volume method. As shown below, when calling a method in the same class, use the object this.

            double volume = this.volume(length, height, width);

Density Driver

Create a class named DensityDriver. Prompt the user to enter the weight (mass), length, height, and width of a container, calculate the density, and print the result.

Geometry Driver

Create a driver class named GeometryDriver that uses the methods in the Geome­try class. Prompt the user to enter the height and width of a rectangle. Calculate and print the perimeter and area of the rectangle. Prompt the user to enter the weight (mass), length, height, and width of an object and calculate and print the volume and density of the object.

Submit Your Assignment

Submit a document with your answers to the questions in green. Submit your Drv.java and Srv.java files along with Geometry.java, GeomTest.java, and PerimeterDriver.java to the L05a dropbox on D2L.

Submit source code files for any of the challenge problems you complete.