Skip to main content
Engineering LibreTexts

12.4: Flow of Execution

  • Page ID
    15231
  • Pulling together the code from the previous section, the complete program looks like this:

    public class NewLine {
    
        public static void newLine() {
            System.out.println();
        }
    
        public static void threeLine() {
            newLine();
            newLine();
            newLine();
        }
    
        public static void main(String[] args) {
            System.out.println("First line.");
            threeLine();
            System.out.println("Second line.");
        }
    }
    

    When you look at a class definition that contains several methods, it is tempting to read it from top to bottom. But that is likely to be confusing, because that is not the flow of execution of the program.

    Execution always begins 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. Instead of going to the next statement, you jump to the first line of the invoked method, execute all the statements there, and 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, we go off to execute the statements in threeLine. While we are executing threeLine, we go off to execute newLine. Then newLine invokes println, which causes yet another detour.

    Fortunately, Java is good at keeping 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.

    In summary, when you read a program, don’t read from top to bottom. Instead, follow the flow of execution.

    • Was this article helpful?