ITEC 120
Writing Methods

Objective

You will call methods, pass values to methods, and write methods. You will also know what a stub method is and you will identify the distinguishing parts of a method signature.

Writing methods

Dowload these two files: Driver.java and Service.java into the same directory and look at the code. It will be helpful to have two windows open side by side so you can see the code in both files at the same time.

The Driver class contains the main method is calls methods in the Service class. Compile both classes and run the Driver. (The Service class can't run by itself. It provides services, or methods, to other classes that use it.)

Notice the mult method in the Service that takes two integers as parameters and returns an integer value. This method has been written for you. See how the method is called in the Driver class. Look at the output of the mult method when you run the driver.

Notice the next mult method in the Service class. This method has not been implemented, but the header for the method has been written and it returns an empty String. This is called a stub method. It compiles and runs, but it doesn't return the correct value. The driver has called this method. Take a look at the output of this mult method.

Implement the second mult method. (Write the code to make it do what it is supposed to do.) Then, recompile both files and run the driver and look at the output. Do you think the method is working correctly?

Now you have two methods with the same name! Both are called mult. What is different about them?


Method Signatures

A method signature uniquely identifies a method. A method signature consists of:

  visibility

  return type

  method name

  (parameters)

For the first two mult methods, the visibility is public and the method name is mult. But, the first returns an int, the second a String. The first has two int parameters, the second has a String and an int.

Now complete the third mult method, which is the same as the second, except that the order of the parameters has been changed. It takes an int and then a String. You will need to add lines of code to the driver to call this method and see if it works.

After you have that method working, try to add the fourth mult method which takes two ints and returns a double. What happens?

What parts of the method signature does the compiler use to uniquely identify a method?

 

containsLower method

Next complete the containsLower method and call it from the driver.

 

Create your own method

Now design your own method. Figure out what you'd like it to do, describe it, write it, and call it from your driver in a similar fashion to the other methods in the Service class.

 

Submit Your Assignment

Submit your Driver.java and Service.java files to the Lab Submission Folder on D2L.