Topic 1 - Variables and Data Types
Topic 2 - Conditionals and Strings
Topic 3 - Loops
Topic 4 - Arrays
Topic 5 - File Handling
Semester 1 Projects
Topic 6 - Classes/Objects and Methods
Topic 7 - ArrayLists
Semester Projects

Methods as actions

Up until this topic, you wrote all your code in the main method, but now we are using lots of methods. Why have multiple methods instead of just one? Procedural Abstraction allows us to name a block of code as a method and call it whenever we need it, abstracting away the details of how it works. This serves to organize our code by function and reduce its complexity and reduce the repetition of code. In addition, it helps with debugging and maintenance since changes to that block of code only need to happen in one place. Here are some of the main reasons to use multiple methods in your programs:

  • Organization and Reducing Complexity: organize your program into small sections of code by function to reduce its complexity. Divide a problem into subproblems to solve it a piece at a time.
  • Reusing Code: avoid repetition of code. Reuse code by putting it in a method and calling it whenever needed.
  • Maintainability and Debugging: smaller methods are easier to debug and understand than searching through a large main method.

Let’s look at an example with lots of repetition of code and create methods to reduce the repetition of code. Run the following code:

Did you find some repeated lines of the This Old Man song? You may have noticed that the chorus is repeated “With a knick knack paddy whack, give a dog a bone. This old man came rolling home.” When you see repeated code, that is a signal for you to make a new method!

There are three steps to creating and calling a method:

  1. Object of the Class: Declare an object of your class in the main method or from outside the class.// Step 1: declare an object in main or from outside the class Classname objectName = new Classname();
  2. Method Call: whenever you want to use the method, call objectName.methodName();// Step 2: call the object’s method objectName.methodName(); //Step 2
  3. Method Definition: write the method’s header and body code like below:// Step 3: Define the method in the class // method header public void methodName() { // method body for the code }

For example, here is a chorus() method definition that we could write for the “This Old Man Song”:

public void chorus()
{
      System.out.println("With a knick knack paddy whack, give a dog a bone.");
      System.out.println("This old man came rolling home.");
}

We can create a Song class, that uses the chorus method. After completing the chorus method, you may call it in main at the appropriate line.

Parameters

You may have noticed more repetition in the song above. What about the lines of each verse? Notice that every word is repeated except the last ones that include a number and a rhyme such as one/thumb and two/shoe.

System.out.println("This old man, he played one.");
System.out.println("He played knick knack on my thumb.");
...
System.out.println("This old man, he played two.");
System.out.println("He played knick knack on my shoe.");

We can make methods even more powerful and more abstract by giving them parameters for data that they need to do their job. We can make a method called verse that takes the number and the rhyme to print out any verse!

public void verse(String number, String rhyme)
{
   System.out.println("This old man, he played " + number);
   System.out.println("He played knick knack on my " + rhyme);
}

Change the song class above to reflect the new verse method. Make sure to call it in main! You should be able to do the following:

      Song mySong = new Song();
      mySong.verse("one", "thumb");
      mySong.chorus();
      mySong.verse("two", "shoe");
      mySong.chorus();

Writing Methods

When you create your own method, the variables you define for it in the method header are called formal parameters. When you call the method to do its job, you give or pass in arguments or actual parameters to it that are then saved in these local parameter variables.

When a method is called, the right method definition is found by checking the method signature or header at the top of the method definition to match the method name, the number of arguments, the data types for the arguments and the return type.

Here’s what that looks like with the 2 method calls above. Notice how the parameter variables get new values with every method call.

Java uses Call by Value when it passes arguments to methods. This means that a copy of the value in the argument is saved in the parameter variable. If the parameter variable changes its value inside the method, the original value outside the method is not changed.

If you pass in an argument that holds a reference to an object, like a String or Person or Turtle object, a copy of this reference is passed in and saved in the parameter variable. The formal parameter and the actual parameter (argument) are then aliases, both refering to the same object. Java was designed this way to avoid copying large objects from method to method. Remember when we discussed reference aliases with turtle objects who are set equal to one another.

Programming Challenge

Here’s another song, The Ants Go Marching, that is very similar to the This Old Man song in its repetitive structure.

 The ants go marching one by one, hurrah, hurrah
 The ants go marching one by one, hurrah, hurrah
 The ants go marching one by one
 The little one stops to suck his thumb
 And they all go marching down to the ground

 The ants go marching two by two, hurrah, hurrah
 The ants go marching two by two, hurrah, hurrah
 The ants go marching two by two
 The little one stops to tie his shoe
 And they all go marching down to the ground

 The ants go marching three by three, hurrah, hurrah
 The ants go marching three by three, hurrah, hurrah
 The ants go marching three by three
 The little one stops to climb a tree
 And they all go marching down to the ground
 
  1. Print out the The Ants Go Marching song and circle the repeated parts of the song.
  2. In the active code window below, create a method or methods that takes parameters to print out a verse. The method(s) should be abstract enough to work for all 3 verses.
  3. In the main method, create an object of the class and call the method(s) you created in the last step to print out 3 verses of the song. Can you add more verses?