Method Types
What You Will Learn
  • void methods vs non-void methods
  • How to define and call a non-void method
  • How to use methods with return type boolean

Method Types

Recall that a method is simply a block of code that is given a name. In Java, there are two types of methods that you can write. These methods are identified by the type of task they perform.

What do the following tasks have in common?

One answer is they are all tasks, that when completed, give you something back. They have an answer, a product, or a result. When you buy a hamburger the restaurant gives you a hamburger, when you bake a cake the result is a nice slice of heaven (I love cake), when you add two numbers together you get a sum, when you withdraw money from the bank you get cash in hand, and so forth.

In Java, methods that give you something back are called non-void methods.

All of the Jeroo sensor methods where non-void methods. There answer was either true or false.

Jeroo Sensor Methods
----------------------------
isClear()
isFacing()
isFlower()
isJeroo()
isNet()
isWater()
hasFlower()

What do the these tasks have in common?

One answer is they are all tasks, that when completed, do not give you anything back. Now there might be a result but the result is not really something you get back. When you clean your room the result is a clean room but that is not something you can take with you. When the task is done it is just done.

In Java, methods that do not give you something back are called void methods.

All of the Jeroo Action methods where void methods. They just performed a task.

Jeroo Action Methods
----------------------------
hop()
give()
pick()
plant()
toss()
turn()

In this lesson, we examine these two types of methods. We will start our discussion with the void method which you are already familiar.

void Methods

Look at the definition of the void method printName. Assume two String variables, lastName and firstName, have been defined as instance variables.

public 
void
printName() { System.out.println("Lastname = " + lastName); System.out.println("Firstname = " + firstName); }

The return type for this method is highlighted in red. The method's return type is declared void therefore it is a void method. This method performs a task but it does not give anything back. It is said to be void of a return value.

Calling void Methods

To execute or call a void method you write the method name along with open and close parentheses. The following example shows the void method being called from the main method.

public static void main(String[] args)
{
   MyClass app = new MyClass();
   app.
printName
(); }

Notice that a void method is called as a single statement on a line by itself.

Methods Called by Other Methods

Methods can be called by other methods. Look at the following example.

public void printName()
{
    
printLastName
();
printFirstName
(); } public void printLastName() { System.out.println("Lastname = " + lastName); } public void printFirstName() { System.out.println("Firstname = " + firstName); }

When method printName is executed it makes a call to method printLastName. When method printLastName completes execution then control is returned to printName where it then makes a call to method printFirstName.

You may have noticed that when a method is called from within the main method dot notation is used.

public static void main(String[] args)
{
   MyClass app = new MyClass();
   
app.
printName(); }

However, when a method is called by another method, that is not the main method, dot notation is not used.

public void printName()
{
    printLastName();
    printFirstName();
}

The reason for this difference has to do with the fact that the main method is declared static.

public 
static
void main(String[] args)

Static methods are covered in another unit. For now just know that if you call a method from within the main method you must use dot notation. If the call is not made from within the main method you do not.

Incidentally there is another situation that requires the use of dot notation and that is when you make a call to a method that belongs to another class. For example, in your class if you make a call to a Scanner method you would use code like the following.

int num = keyboard.nextInt();

Non-void Methods

All of the Java standard library methods you have used in your programs so far were actually non-void methods. Here is a list of some of them.

Java - Math Class
----------------------------
sqrt()
min()
max()
round()

Java - Scanner Class
----------------------------
nextInt()
nextDouble()
nextLine()
next()

Java - String Class
----------------------------
equals()
length()
substring()

Java - Integer Class
----------------------------
parseInt()

Non-void methods differ from void methods in that they give something back. What they "give back" is dependent upon their return type. Let's look at an example. Assume that the variables, num1 and num2, have been declared as instance variables of type int.

public 
int
sum() { return num1 + num2; }

The return type for method sum is highlighted in red. The return type declares what the method is going to "give back" or return. The keyword return is required in all non-void methods. Since the method sum has a return type of int the return line is required to return a value of this type.

A non-void method's return line can be just about anything as long the code after the return matches the return type. Here are some examples.

A method can return a literal value.

return 500;
return 98.6;
return "John Wayne";
return true;

A method can return the contents of a variable.

return average;
return name;

A method can return the result of a mathematical expression.

return 15 * 7 + 20;
return (num1 + num2) / 2;

A method can return the result of a boolean expression.

return num > num2;
return num != 0 && num < 1000;
return lastName.equals(name);

Calling non-void Methods

The way that a non-void method is called differs from the way that a void method is called in that the call is made from within other Java statements. Since a non-void method always returns a value, this value has to be stored in a variable, printed, or returned to a Java control structure or another method. Here are some examples.

The method call can be in an assignment statement.

int num = sum();
double avg = calculateAverage();
String name = getName();

The method call can be in a print or println statement.

System.out.println("The sum is " + sum());
System.out.println("Avg = " + calculateAverage();
System.out.println(getName() + " is my name");

The method call can be inside a Java structure such as an if statement or looping structure (you will learn about loops in the next unit).

if(sum() > 500)
if(calculateAverage() == 100)
if(getName().equals("John Wayne"))
while(!getName().equals("stop")

The method call can be on the return line of another method.

return sum() / numItems;
return calculateAverage() > 70;

The demonstration below shows the order of execution for a non-void method.

Boolean Non-Void Methods

A common type of non-void method is a method that has a return type of boolean. Recall that a boolean value can only be either true or false.

Programming Note: all of the Jeroo sensor methods have a return type of boolean.

Let's look at an example. Assume that the variables, num1 and num2, have been declared as instance variables of type int.

public boolean isBigger()
{
   if(num1 > num2)
      return true;
   else
      return false;
}

Method isBigger returns a value of true if num1 is greater than num2; otherwise it returns a value of false.

This method could also have been written like the following.

public boolean isBigger()
{
    return (num1 > num2);
}

The boolean expression (num1 < num2) evaluates to either true or false which is then returned by the method.

Programming Note: methods that return a boolean value often have the word "is" placed in front of the method name. (Ex. isWater, isJeroo, isBigger)

Calling Boolean Non-Void Methods

Boolean non-void methods are called in the same way as other non-void methods. Their return value needs to be stored in a variable, printed, or returned to a Java control structure or another method.

Here are two examples.

boolean result = isBigger();   
// return value stored in boolean variable
if(isBigger())
// returned within an if statement
{
// do something
}

Non-Void Methods with Multiple Return Lines

A non-void method can have more than one return line. Look at the example.

public String getSeason(int month)
{
   if(month == 1 || month == 2 || month == 12)
      return "winter";
   if(month == 3 || month == 4 || month == 5)
      return "spring";
   if(month == 6 || month == 7 || month == 8)
      return "summer";

   return "fall";

Given a month of the year, method getSeason returns one of four string values. Once a return line is executed the method is complete and control is returned back to where the method was called. All code below the return line is not executed. The use of multiple return statements makes the use of if-else statements unnecessary.

Notice that the "fall" return line is not in an if statement.

return "fall";

This is required. When you place return statements inside if statements you must have at least one return that is not in an if statement; otherwise you will get a "missing return statement" compiling error.