Writing Methods

A method (like main) is a block of code within a class that can be called within the class.  The code within the block is executed when the method is called.

We often create a method when a block of code needs to be executed repeatedly.  Rather than have multiple copies of the same block of code, we can put one copy of the code in a method and repeatedly call the method.  We also create method simply to organize our code.

The General Form of a Method

modifier return_type  method_identifier(parameter_list) {
    ...
    return_statement;
}

Example 1

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int b = sc.nextInt();
    int h = sc.nextInt();
    int area = computeArea(b,h);  // method call
    if (area > 0) {
        printArea(area);
    }
}

static int computeArea(int base, int height) {  // method definition
    if (base <= 0 | height <= 0) {
        return -1;
    } else {
        return base * height;
    }
}

static void printArea(int a) { // method definition
    System.out.printf("Area: %d\n", a);
}

Variable Scope

  • Parameters (primitive vs. reference)
  • Local Variables
  • Returning values

Example 2

public static void main(String[] args) {
    String input = getName();
    greetPerson(input);
}

static String getName() {
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter your name: ");
    String name = sc.next();
    return name;
}

static void greetPerson(String name) { 
    System.out.println("Hello" + name); 
}

Arrays

Arrays are containers that can hold multiple values of the same data type.

Declaring Arrays

We can declare a reference to an array as follows.  These statements don’t, however, allocate memory for the array.

String args[];
String[] args;

int heights[];
int[] heights;

Allocating Arrays

In order to allocate space you need to use the new keyword and specify either the size or a list of initial elements.

String[] arr1 = new String[3];  // elements initialized to null
int[] arr2 = new int[12];       // elements initialized to 0

String s1 = "one";
String s2 = "two";
String[] arr3 = {s1, s2, "three"};
int[] arr4 = {10, 20, 17};

arr3 = new String[] {"four", "five"};  // array declared earlier
arr4 = new int[] {31, 47};             // array declared earlier

Accessing Elements of an Array

We can get the value stored at a particular index in the array using brackets and the index.

String first = arr3[0];
int last = arr4[1];

Arrays are implemented as objects on the heap and have a length property that can be used to get the size of the array. Note that length is not a method, but rather a property.  We can access properties (a.k.a. fields) using the dot operator as we did with methods, however we omit the parenthesis.

System.out.println("Size: " + arr4.length);   // prints 2

We can access all of the elements in an array using a for-loop to iterate over all of the possible array indices.  In the example below, we initialize all of the elements in the array to 1.

for (int i = 0; i < arr4.length; i++) {
    arr4[i] = 1;
}

For-each Loops

For-each loops allow us to iterate through all of the elements in the array without having to use indices.  For-loops can not be used to modify an array( add element, remove element, change element), but are useful when you need to process each element.

for (int element : arr4) {
    System.out.printf("%d ", element);
}

Arrays are Reference Types

  • Stored on the heap
  • We can pass references to arrays into functions
  • Arrays passed into a function can be modified within the function
  • We can return reference to arrays.
  • Memory is reserved so long as it is referenced by some variable.

Passing and Returning Arrays

public static void main(String[] args) {
    int[] ages = initArray(10);
    System.out.println("Total ages: " + sum(ages));
}

static int[] initArray(int size) {
    int[] arr = new int[size];

    for (int i = 0; i < arr.length; i++) { 
        arr[i] = i; 
    }

    return arr;
}

static int sum(int[] arr) {
    if (arr == null) {
        return 0; 
    }
    int sum = 0;
    for (int elm : arr) {
        sum += elm;
    }
    return sum;
}

Notice that we check to see if arr is null in the sum function.  Before ever calling a method or accessing a field on a reference type variable, make sure it is not null (or use a try-catch statement).

Array Examples

Searching For an Int in and Array of Ints

Consider the following block of code:

int[] array = new int[5];            // All elements initially 0
array[0] = 1;
array[1] = 3;
array[2] = 5;

boolean found = search(array, 3);    // found is true
found = search(array, 2);            // found is false
found = search(array, 0);            // found is true

Write a method named search that has two parameters.  The first parameter is a reference to an array of integers and the second parameter is an integer.  The method returns true if the value of the second argument is an element in the array referenced by the first.  Otherwise it returns false.

private static boolean search(int[] array, int num) {
    boolean found = false;
    for(int i = 0; i < array.length; i++) {
        if (array[i] == num) {
            found = true;
            break;
        }
    }
    return found;
}

Adding Unique Elements to an Array Using Search

Write a block of code that repeatedly asks the user to enter an integer until the user has entered 5 different numbers.

Scanner sc = new Scanner(System.in);
int[] array = new int[5];
int numElements = 0;

while (numElements < 5) {
    System.out.println("Please enter an integer:");
    int num = sc.nextInt();
    boolean found = search(array, num);
    if (!found) {
        array[numElements] = num;
        numElements++;
    }
}

Searching For a String in an Array of Strings

Consider this code:

String[] array = new String[5];
array[0] = "One";
array[1] = "Two";
array[2] = "Tee";

boolean found = search(array, "Tee");   // found is true
found = search(array, "Red");           // found is false
found = search(array, null);            // found is false

Write a method named search that has two parameters.  The first parameter is a reference to an array of Strings and the second parameter is a reference to a non-null String.  The method returns true if the String referenced by the second parameter is in the array referenced by the first parameter. Otherwise it returns false.

boolean search(String[] array, String word) {
    for(int i = 0; i < array.length; i++) {
        if (array[i] == null) {
            return false;
        }
        if (array[i].equals(word)) {
            return true;
        }
    }
    return false;
}

Varargs – Variable Length Arguments

When we define a function we may want to allow the user to pass an arbitrary number of arguments into the function.  We can do this with varargs.  A vararg (variable-length argument) is specified with three periods (…) between the type and variable name in the function’s parameter list as shown below.

static void printNames(String ... names) {
    ...
}

This syntax tells the compiler that printNames can be called with zero or more String arguments.  Internally, names is declared as an array of type String that we can access as normal.

static void printNames(String ... names) {
    for (String name : names) {
        System.out.println("Name: " + name);
    }
}

A function can also have other parameters in addition to a variable length argument, however the variable length argument must be the last parameter listed.

static void printNames(String greeting, String ... names) {
    for (String name: names) {
        System.out.println(greeting + " " + name);
    }
}

 

Restriction:  There can be only one variable length argument.