Functions

One function can call other functions. In this example, verse calls chorus.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Old MacDonald
package farm;
import java.util.*;
public class FarmAnimals {
    public static void main(String[] args) {
      verse("cow","moo");
      verse("pig","oink");
      verse("cat","meow"); 
  }//main
  public static void chorus() {
    	System.out.println("Old MacDonald had a farm, E I E I O");
  }//chorus
  public static void verse(String animal, String sound) {
		chorus();
		System.out.println("And on the farm he had a "+animal+" E I E I O");
		System.out.print(sound+" "+sound+" here ");
		System.out.println("and "+sound+" "+sound+ " there");
		System.out.println();
  }//verse
}//class
CODE

Output:

Old MacDonald had a farm, E I E I O
And on the farm he had a cow E I E I O
moo moo here and moo moo there

Old MacDonald had a farm, E I E I O
And on the farm he had a pig E I E I O
oink oink here and oink oink there

Old MacDonald had a farm, E I E I O
And on the farm he had a cat E I E I O
meow meow here and meow meow there

NEXT: