Home CPSC 220

Functions

 

Overview

The programs we have written so far have had all of our code in the "main" function. This is fine for small programs, but as we write larger programs, it becomes unwieldy.

Rather than have all of our code in main, we can split our code into different functions. This has two main benefits:

  1. It breaks the code up making it easier to follow.
  2. We can reuse the code in the function in multiple places.

Functions are also sometimes called methods, procedures or routines.


 

Calling Built-In Functions

Java comes with lots functions in the standard library, some of which we have called already. What functions are called in the code below::


import java.util.Scanner;

public class Roots {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a value: ");
        double value = in.nextDouble();
        double root = Math.sqrt(value);
        System.out.println("Square root of " + value + " = " + root); 
    }
} 

Why would we want to have a function for "sqrt" as opposed to just inserting the code for the calculation directly into main?


 

Writing Functions

In Java we can define our own functions that can be used like the built-in ones. Below is a very simple function that takes two parameters, and returns their sum:


public class Functions {
    
    // this function takes to numbers and returns their sum
    public static int add(int a, int b) {
      return a + b;
    }

    public static void main(String args[]) {
        int sum = add(5, 7);
        System.out.println("5 + 7 = " + sum); 
    }
}

This example shows the form of functions in Java. The function is defined first, then we can call it.

When we call a function, the program switches into it and begins executing it. When a function returns, we go back to the function that called it (main in this case).

Functions also create their own scopes. The variables "a" and "b" can only be accessed inside of the "add" function.

The general form of a function is given below:


return-type name(param1type param1name, param2type, param2name...) {
    body
}

Functions can have any number of parameters, but only one return value. In Java, we must declare the return and type of each parameter!


 

Example: Absolute Value

The absolute value of a number is it's non-negative value ignoring sign. How could we write a function that takes a number as a parameter and returns its absolute value?



 

Example: Leap Years

The following program is one that computes whether a given year is a leap year or not.

import java.util.Scanner;

public class Leap {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter year: ");
        int year = in.nextInt();

        boolean leapyear;
        if ((year % 400) == 0) {
            leapyear = true;
        } else if ((year % 100) == 0) {
            leapyear = false;
        } else if ((year % 4) == 0) {
            leapyear = true;
        } else {
            leapyear = false;
        }

        if (leapyear) {
          System.out.println("This IS a leap year!");
        } else {
          System.out.println("This is NOT a leap year!"); 
        }
    }
}
How can we change this program so that it splits the logic for this into a separate function?


 

void functions

Not all functions need to return a value. Sometimes a function's job is to print something, or take some other action that does not produce a result. This can be done with a "void" function:


public class Repetition {

    public static void printMessage(String message, int times) {
        for (int i = 0; i < times; i++) {
            System.out.println(message);
        }
    }

    public static void main(String args[]) {
        printMessage("Hello ", 10);
        printMessage("There", 5); 
    }
}

void functions can still have return statements, they just don't return any value.


 

Example: Times Tables

How could we write a program to print a multiplication table? The program should work for any size table. What functions should we use?


 

Designing Functions


 

Commenting Functions

It's good practice to include a comment at the top of every function indicating what the job of the function is, as well as what the parameters and return value mean. For example:


/* printMessage takes a message and a count as parameters
   it will print out the message count number of times and
   then return */
public static void printMessage(String message, int times) {
    for (int i = 0; i < times; i++) {
        System.out.println(message);
    }
}

This demonstrates the /* */ style comments which are used in Java for longer comments.

In future programming assignments, you will need to provide this type of "synopsis" comment for each function (not needed for labs).

Copyright © 2024 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.