Void Methods


What is a method?

A method is a set of code that is grouped together under one name to perform a specific task. You’ve seen methods before when you used pre-written methods, like readLine(), println(), or parseInt().

To do this task, someone out there has written the set of code for you that tells the computer to do this, and you “call” that set of code through the method’s name. Now, we want to write our own custom methods.

Why should I write methods? Why can’t all my code just exist in main()?

It’s sloppy. Methods are a way to organize your code and make it more readable for you and any other programmers that may need to understand your code.

Compare the two programs below.

This program has one long, complex method containing all statements necessary to solve the problem...

This program has been divided into smaller problems, each handled by a separate method...

public class BigProblem {

   public static void main(String[] args) {

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      statement;

      ...

   }

}

public class DividedProblem {

   public static void main(String[] args) {

      method2();

      method3();

   } // end main

   public static void method2() {

      statement;

      statement;

      statement;

   } // end method2

   public static void method3() {

      statement;

      statement;

      statement;

   } // end method3

}

A better reason for methods is the divide & conquer problem-solving strategy.

The idea is that smaller problems are easier to solve than bigger ones. So by breaking up your program’s overall task into smaller, more manageable pieces, a large problem divided into several smaller problems becomes easier to solve than trying to tackle it all at once.

It also helps with debugging. For instance, if you knew a problem was occuring with step 1 of your problem, you only need to look at the method that is responsible for executing step 1.

Finally, it can make your code more readable with code reuse. Think of it like reusable water-bottles versus grocery store water-bottles.

If a specific task is performed several times throughout your program, a method can be written once to perform that task, and then be called upon every time that task is needed. Without methods, you’d have to copy-paste a whole lot!

Types of Methods

We will cover two general categories of methods: void methods and value-returning methods. A void method is one that simply performs a task and then terminates.

For example, println() is a void method...

int num = 16;

System.out.println(num);

num = 0;

In this example, we called the method System.out.println() and passed in the argument “num”. With num, println() did it’s job of printing out the value of num to the console, and then terminated. The code then resumes to change the value of num to 0.

A value-returning method not only performs a task, but also sends some data back to the code that called it.

For example, Integer.parseInt() is a value-returning method...

String num = "-3";

int intNum = Integer.parseInt(num);

System.out.println(intNum);

In that example, we called Integer.parseInt(), a method that returns an integer version of the variable passed in (if possible). We passed in num, which was -3. Integer.parseInt(num) will return a value of 3, and we store that value into a new variable, intNum. When we print out intNum, a “3” is printed to the console.

Defining a void method

To create your own method, you must write its “definition”, which consists of two parts: a header and a body.

The method header occurs at the beginning of the definition. For example, main()’s header is…

public static void main(String[] args)

Then the body of the method’s definition is everything else…

{

   // Replace with code

}

Every complete Java program must have a main() method. But we can, and should, also write other methods as well.

For example, this is a simple method that writes some text to the console...

/**

 * Writes an informative message to the console.

 */

public static void displayMessage() {

   System.out.println("Hello from the displayMessage method!");

} // end displayMessage

Calling a method

In order to use our methods, we need to call them! The exception to this is the main() method, which automatically is called when the program starts.

You have had plenty of practice calling a method, but to call displayMessage() from earlier...

displayMessage();

This will cause the code to jump down to your code inside the method displayMessage(), execute that code, then jump back and continue to the next line.

For example...

1    public class Main {

2       public static void main(String[] args) {

3           System.out.println("Hello from main!");

4           displayMessage();

5           System.out.println("Back in main!");

6       } // end main

7

8    /** 

9     * Writes an informative message to the console.

10    */

11      public static void displayMessage() {

12          System.out.println("Hello from displayMessage!");

13      } // end displayMessage

14    }

When the program starts, the code runs line 3. Then on line 4, displayMessage() is called. The code will jump to that method and will run the code inside the body of that method (line 9). Once the last line in the called method is complete, the code will jump back to the line after displayMessage() was called, line 5 to continue.

The output will be:

Hello from main!
Hello from displayMessage!

Back in main!


From a loop

Methods can be called from within loops and control structures, like if-statements.

For example...

public class Main {

    public static void main(String[] args) {

        System.out.println("Hello from the main method!");

        for (int i = 0; i < 5; i++) {

            displayMessage();

        }

        System.out.println("Back in the main method!");

    } // end main

    /**

     * Writes an informative message to the console.

     */

    public static void displayMessage() {

        System.out.println("Hello from the displayMessage method!");

    } // end displayMessage

}

Hello from the main method!

Hello from the displayMessage method!

Hello from the displayMessage method!

Hello from the displayMessage method!

Hello from the displayMessage method!

Hello from the displayMessage method!

Back in the main method!

From another method

Methods can also be called in a layered, or hierarchical fashion! In other words, method A can call method B, which can call method C. When C finishes, we return to B. When B finishes, we return to A, and when A finishes we return to main.

public class Main {

    public static void main(String[] args) {

        System.out.println("I am starting in main.");

        deep();

        System.out.println("I have resurfaced in main!");

    } // end main

    /**

     * Writes a message to the console for the middle level of code.

     */

    public static void deep() {

        System.out.println("I am now in deep!");

        deeper();

        System.out.println("I have risen back to deep!");

    } // end deep

    /**

     * Writes a message to the console for the deepest level of code.

     */

    public static void deeper() {

        System.out.println("I am now in deeper!");

    } // end deeper

}

I am starting in main.

I am now in deep!

I am now in deeper!

I have risen back to deep!

I have resurfaced in main!

Documenting a method

Method header comment

A method header should always be written -- it’s like common courtesy. For now, a method header should provide a brief explanation of the method’s purpose. As our methods get more complicated, we will add more things to the method header. But for now, a brief ( < 1 sentence) will usually do.

Notice that throughout the note there have been method headers in each example.

Method headers start with /** on its own line. Each subsequent line afterwards includes a * in line with the first. The last line is */, which is also inline with the first asterisk (*) from the first line.

/**

 * Purpose of the method goes here…

 */

The reason why we format our headers like this is because these types of comments can be read by a program named javadoc, which produces HTML documentation.

Beyond that, method header comments are good for all the reasons that commenting is useful… Making your program more readable and easy to understand to a third-party, and for debugging or later code updates.

Commenting throughout

Commenting throughout should exist as you would normally. Explain any weird logic or variable names that may not be self-explanatory.

End comment

You’ll also notice that throughout the note, there has been another recurring comment.

This one is a // comment, which occurs at every closing curly bracket, }.

This is to help us keep track of which body of code or code structure we are in, so that we don’t get lost in all the brackets, or accidentally add a line of code to the wrong section of our program.