2. Method Fundamentals

2.1. Objectives

  • Describe what is meant by flow of control
  • Write a static void method

2.2. Time Goal

  • 25 minutes on this section

2.3. Key Terms

flow of execution
The order in which Java executes methods and statements. It may not necessarily be from top to bottom in the source file.
invoke (call)
To cause the code in a method to execute. Also known as “calling” a method
decomposition (divide-and-conquer)
A common problem-solving technique is to break problems down into sub-problems. This technique is also called divide-and-conquer.

2.4. Exercises

Note

Some methods perform a computation and return a result. For example, Math.sqrt(25) returns the value 5.0. Other methods (including main) carry out a sequence of actions, without returning a result. Java uses the keyword void to define such methods. Here’s a simple example:

The name of the class is NewLine. By convention, class names begin with a capital letter. NewLine contains two methods, newLine and main. Remember that Java is case-sensitive, so NewLine and newLine are not the same.

Run the example and observe the output

Method names should begin with a lowercase letter and use “camel case”, which is a cute name for jammingWordsTogetherLikeThis. You can use any name you want for methods, except main or any of the Java keywords.

newLine and main are public, which means they can be invoked (or called) from other classes. And they are both void, which means that they don’t return a result (unlike the Math methods, for example).

The output of this program is:

First line.

Second line.

Notice the extra space between the lines. If we wanted more space between them, we could invoke the same method repeatedly. Or we could write yet another method (named threeLine) that displays three blank lines.

In the following program, the main method invokes (executes the code in the method) threeLine, and threeLine invokes newLine three times. Because newLine is in the same class as threeLine, we don’t have to specify the class name like NewLine.newLine().

Run the program and observe the output.

    Q-92: In the program TripleNewLine modify the newLine method by replacing System.out.println("x"); with System.out.println("x");
  • x
    x
    x
    Second line.
    
  • Incorrect
  • x
    x          
    x
    x
    x
    
  • Incorrect
  • First line.
    x
    x
    x
    Second line.
    
  • Correct
  • x
               
             
             
    x
    
  • Incorrect
  • No output is generated after making the change
  • Incorrect
    Q-93: Which of the following would best follow the naming convention for a Java method that returns the current price of a stock?
  • x
  • Incorrect, in general the method name should be descriptive of what it does
  • _get_stock_price
  • Incorrect, this name is descriptive of what the method does but not "camel-case"
  • Getstockprice
  • Incorrect
  • GetStockPrice
  • Incorrect
  • getStockPrice
  • Correct, this is an example of "camel-case" naming which is the convention for Java methods and is descriptive of what the method does.

What is another name for calling a method?

Note

When you look at a class definition that contains several methods, it is tempting to read it from top to bottom. But that is not the flow of execution, or the order the program actually runs. For example, the NewLine program runs methods in the opposite order than they are listed.

Programs always begin at the first statement of main, regardless of where it is in the source file. Statements are executed one at a time, in order, until you reach a method invocation, which you can think of as a detour.

When a method is invoked, instead of going to the next statement:

  1. your program jumps to the first line of the invoked method,
  2. executes the statements within the method, and
  3. then come back and pick up exactly where you left off.

That sounds simple enough, but remember that one method can invoke another one. In the middle of main, the previous example goes off to execute the statements in threeLine`. While in ``threeLine, it goes off to execute newLine. Then newLine invokes the System method println, which causes yet another detour.

Java keeps track of which methods are running. So when println completes, it picks up where it left off in newLine; when newLine completes, it goes back to threeLine; and when threeLine completes, it gets back to main.

Beginners often wonder why it’s worth the trouble to write other methods, when they could just do everything in main. The NewLine example demonstrates a few reasons:

  1. Creating a new method allows you to name a block of statements, which makes the code easier to read and understand.
  2. Introducing new methods can make the program shorter by eliminating repetitive code. For example, to display nine consecutive newlines, you could invoke threeLine three times.
  3. A common problem-solving technique is to break problems down into sub-problems called decomposition or divide-and-conquer. Methods allow you to focus on each sub-problem in isolation, and then compose them into a complete solution.
  4. Perhaps most importantly, organizing your code into multiple methods allows you to test individual parts of your program separately. It’s easier to get a complex program working if you know that each method works correctly.
        Q-95: Q-94: 

Order the method calls and returns to follow the flow of control of the PrintTwice program

public class PrintTwice {

   public static void printTwice(String s) {

      //Invoke the println method
      System.out.println(s);

      //Invoke the println method a second time
      System.out.println(s);
   }

   //Main method
   public static void main(String[] args) {
      //Invoke the printTwice method
      printTwice("Don't make me say this twice!");
   }
}
Start in main method --- Invoke printTwice method --- Invoke println method Return void from println method Invoke println method Return void from println method --- Return void from printTwice method --- Return void from main method ---

Note

You can visualize the flow of execution for this program in the below visualization tool

Click to visualize program execution and then click on the forward button to move through the program step by step.
Next Section - 3. Method Components