Program Logic

Unit 5 Index

Void Methods

Void Methods

This chapter, focuses on methods with void as their return type and we fine tune what we already learned in the previous chapter. Remember, dividing your code into logical sections, makes your code easier to read and debug. Some of my code examples contain methods. Simplistically stated, when you divide your program into logical blocks of code, it is modularized. Each method should have one primary task. Limiting the task that a method does, makes the method more reusable. Programs should be modularized for efficiency.

Keep in mind, the code is not done, until it is done. I know that sound ridiculous, but as you are thinking through and then coding a solution, you may end up changing the signature of your methods and its code. Whenever you create a program, write a small bit of code, test, and repeat.

Methods in your Projects

Remember in Java, all methods are coded within a class. Each method has a signature followed by a beginning curly brace, your code that does the work, and finally an ending curly brace. I always type an open curly brace ( { ) and then immediately type a closing curly brace ( } ) that way I do not forget to close the method body. I then press enter to make an empty line. This helps me to keep my code inside the body. The body says “the lines of code within my curly braces belong together”. I highly recommend that you place a comment to the right of your ending method and class curly braces to identify each one. This also helps you keep your code within your methods and your methods within the class.

Naming Methods

Remember, method names should start with an action verb. Also in Java, the first “word” of the method name starts with a lowercase letter and subsequent “words” start with an uppercase letter. This naming convention is called camel case.

Remember, a method with a return type of void does not return anything to the caller. Sometimes these method names start with words such as “set”, “fill”, or “display”. This is not a hard and fast rule, but it should help you when choosing method names.

(Re)using Methods

We use methods because they are a great way to organize your code so it is easier to read and maintain. If you call a method more than once in a program, it is being reused. Well designed methods can also be used in more than one application. For our purposes, copy and paste will be the mechanism for reusing a method within another program.

Remember, methods are used to break a problem into small manageable parts. Basically, divide and conquer should be your mantra. Think about displaying the results of calculated values. Basically, they are all the same...displayed text.

The displayMessage() method below accepts a String parameter named results. All the method does is display those results. This is a very simple example of re-usability. All you do is send a String into the method and the method does the work. Please remember, your String should include some explanatory text.

private void displayMessage(String results){

    System.out.println( results );
	
}//end of displayMessage

Who is in Charge?

Many students wonder, who is in charge, the caller or the method. Make no mistake about it, the method is in charge. The method says, if you want to use me, you MUST send me what I want. Remember, sometimes the method does not want anything. However, in the case of displayMessage(), as coded in the above example, you MUST send in a String variable. Remember, the data types and order of the parameters matters! The method says, send me what I want and make sure the data types match and you send them in the order they are listed in the method signature. Oh, yeah, and by the way, when you are calling me, I really do not care if you use the same variable names as I have in my signature.

Another important tidbit is that your method signatures must be unique within the same class. Overloading a method means you have two or more methods that have the same name, however, their signatures differ so that the Java engine looks at them as being unique. As you can imagine, there are rules that determine if the methods are different enough to be considered overloaded. In Program Logic, you can just give all your methods a unique name. However, if you are curious, feel free to Google “Java overloaded methods”. If you understand it, go ahead and use them.

Signature of a void Method

Remember, each method signature is made up of the same pieces parts; a modifier, return type, method name, and parentheses. Remember, any data inside of parentheses is generically called a parameter. You can have zero or more parameters in your method signature. Parameters, which are just variables being accepted into a method signature, always contain a data type.

In this course, we will use private as the access modifier for all of our methods, except main() and our constructor. An access modifier of private means that your method cannot be seen outside of its containing class. The return type void means the method does not return a value to its caller.

Below is a method signature that does not accept parameters, nor does it return a value. You can tell because the return type is void and nothing is between the parentheses. Remember though, methods, including constructors, can accept parameters.

non-static method

One Primary Task

Completing the 5-Step Solution Algorithm helps you determine your processes, which translate into methods. Discovering the primary tasks of your methods helps to decide whether or not the method needs parameters and whether or not the method should return a value. Remember, this section focuses on the return type of void, so for now, let's just look at parameters.

Test Your Knowledge - Interactive Activity

Below is a problem statement and interactive activity. The activity is designed to help you divide a problem statement into desirable methods. After carefully reading the problem statement, please complete the activity.

A program is required to prompt the end-user for the maximum and minimum temperature readings on a particular day, accept those readings as integers, and calculate and display to the screen the average temperature, calculated by (maximum temperature + minimum temperature)/2.
          

How many methods are needed to solve the problem. Keep in mind, we need to divide and conquer. Press submit to check your answer.

1
2
3
To many to count

Calling Methods

It is not enough to just code a method, you also need to call the method. You call a method when you want to run the code within the method body. A method just sits there waiting to be called into action, so it does NOT matter which order your methods are written within the class. But it matters greatly which order you call the methods. Also note, methods can be called from almost anywhere in your code. You need to call a method “just in time to use it” and remember: ORDER MATTERS!

A method signature always includes the parentheses. The parentheses can be with or without parameters. Remember, if the method is expecting parameters, you need to supply the parameters when calling the method. Technically, when data is supplied in the call, the data is referred to as arguments. When the data is received in the method signature, the data is referred to as parameters.

Below are some calls to methods that are needed in our problem statement. Notice some include arguments within the parentheses and no data types. This is because the data types are already be known within the method that created the variables.

getUserInput();
calculateAverage(minTemperture, maxTemperature);
displayMessage(average);

Think Logically

Logic must prevail when calling methods. Looking at the above calls you know the method calculateAverage() needs two variables because the call is sending two arguments. But where are the variables declared? Logically speaking, they are declared in the method getUserInput(). It is also safe to assume that getUserInput() supplies values to the variables minTemperture and maxTemperature. Remember variable scope. Since the variable values are supplied within getUserInput(), then it is logical to assume the call to calculateAverage() happens when those variables and their values are known. In other words, after both the variables have valid values, call calculateAverage() passing it the variables.

Let's spin the logic out a bit further. Based on our example, the variable average should get its value AFTER the average is calculated. The code may look something like: average = (low + high)/2.0; Following the example, it is safe to say that displayMessage() is called after average has its value.

Logically, you could:

  1. call getUserInput() from within the constructor
  2. call calculateAverage() from within getUserInput(), but AFTER the variables have valid values.
  3. call displayMessage() from within calculateAverage(), but AFTER the variable average has a valid value. Better yet, send a nice message that includes the average temperature to displayMessage()

IMPORTANT! The data types of the arguments and the order of the arguments MUST MATCH the data types of the parameters and the order of the parameters. The names do not need to match.

What's next?

The next item in this unit is Methods that Return a Value.