3. Methods and Arrays

What We Will Cover


Illuminations

Review of Assignment

  • A2: Decimal Palindromes
  • How did you handle isolating single digits?
  • How did you handle rounding errors?
  • Did your program work with the tests?

Viewing WebCT Assignment Results

3.1: Methods

Objectives

At the end of the lesson the student will be able to:

  • Create and call methods
  • Pass values to methods
  • Overload methods
  • Exit methods

3.1.1: About Methods

Method -- a function, procedure or routine that executes a piece of code when called.

Why Methods?

  • Methods allow grouping of related code that performs specific task
  • Aids in structuring code
  • Makes program development more manageable
  • Makes it easier to reuse sections of code
  • Rule of thumb: If you repeat the same sequence of 3 or more lines more than once, you should create a method for the task performed.

Using Methods

  • Methods are invoked by a method call
  • Arguments are used to communicate information between methods
  • Methods return a result to calling method (caller)
  • Similar to a boss (caller) asking a worker (called method) to complete a task

3.1.2: Mathematical Methods

  • Java has many methods in the API libraries
  • One example is the Math class
  • Methods include: pow, sqrt, max, min, random, sqrt, log, and trig functions
  • Also includes common math constants:
    • Math.PI (approximately 3.14159)
    • Math.E (base of natural logarithms, approximately 2.718)
  • In addition, includes three similar methods: round, floor, and ceil
  • All three return whole numbers, although they are type double
  • Math.round returns the whole number nearest its argument
  • Math.floor returns the nearest whole number that is equal to or less than its argument
  • Math.ceil (short for ceiling) returns the nearest whole number that is equal to or greater than its argument
  • Method Result
    Math.round(3.3) 3.0
    Math.round(3.7) 4.0
    Math.floor(3.3) 3.0
    Math.floor(3.7) 3.0
    Math.ceil(3.3) 4.0
    Math.ceil(3.7) 4.0

Method random

  • Random numbers are a series of numbers whose order cannot be predicted
  • Many computational problems need use of random numbers
  • Hard to find truly random numbers, even in real life
    • Dice never perfect
    • Cards never shuffled completely randomly
    • Computers can only handle numbers within a finite range and limited precision
  • Best that can be done in most cases is generate psuedorandom numbers
    • Sufficiently random for the task at hand
  • Math.random produces series of psuedorandom numbers
    • Range is 0.0 up to, but not including, 1.0
    • Returns a double-precision value

Scaling and Shifting

  • Since the range of Math.random is between 0.0 and 1.0, will need to scale for your application
  • Also may need to shift the starting point of the numbers
  • General form for producing integer random numbers for an application:
  • shiftingValue + (int) (Math.random() * scalingFactor);
    
  • For example, to simulate a single 6-sided die with random numbers:
  • int dieFace = 1 + (int) (Math.random() * 6);
    

3.1.3: Defining Methods

  • Programmers can write customized methods
  • Syntax:
  • returnValueType methodName(arguments) {
        ....
    }
    
  • Begins with the data type of the value that will be returned
    • Can be any primitive type (char, int, double, etc.) or class (String, etc.)
    • When no values are returned, use the special type: void
  • After specifying the data type, give the method a name
  • Following the name, add a set of parentheses ()
  • Within parenthesis are the arguments that are passed, if any
  • Code executed by the method is enclosed in brackets {...}
  • After the method is finished, program continues at the line after the call
  • Can use a method anyplace where it is legal to use its return type

For Example

  • Following code has two methods
  • public class Square5 {
        public static void main(String[] args) {
            double result = square(5);
            System.out.println(result);
        }
    
        static double square(double x) {
            return x * x;
        }
    }
    
  • Method main calls method square, passing an argument of 5
  • Method square takes the argument, computes the squares and returns the result
  • What would be returned if we passed square an argument of 4?

Method Naming Conventions

Static Methods

  • Until we cover objects, all our methods must use the qualifier static
  • If you forget the static keyword, you get a message like:
  • Can't make static reference to method
    

3.1.4: Passing Values

  • Passing values to methods increases their usefulness and flexibility
  • Input values for methods are called arguments or passed values
    • Within the method, the values that are passed are called parameters
  • Can pass zero, one or more arguments to a method
  • Definition of method must specify data types and names to "catch" arguments
  • Calling method must put values of the same data type, in the same order, inside the parentheses

For Example

public class Square5 {
    public static void main(String[] args) {
        double result = square(5);
        System.out.println(result);
    }

    static double square(double x) {
        return x * x;
    }
}

Passing Primitive Data Types

  • All types in Java are passed-by-value (a.k.a. call-by-value)
  • When method is called, value of each argument is copied to its corresponding parameter
  • Variables used as arguments cannot be changed by the method
  • Method only gets a copy of the variable's value

Coercion of Arguments

  • Coercion: forcing arguments to appropriate type before passing to a method
  • Java automatically casts narrower data types to broader data types
  • byte => short => int => long => float => double
                    /
             char =/
    
  • In our example, coercion was used when passing 5 to method square
    • 5 is an integer
    • Method square expects a double
  • Can also coerce the evaluation of methods
  • For example:
  • System.out.println(square(5));
    
  • Since square(5) is not something that can be used directly
    • First evaluates: square(5)
    • Then evaluates: System.out.println()

3.1.5: Returning A Value

Return Statement

  • Methods that return a value must execute a return statement
    • Also must include the value to return
  • For example:
  • public class Square5 {
        public static void main(String[] args) {
            double result = square(5);
            System.out.println(result);
        }
    
        static double square(double x) {
            return x * x;
        }
    }
    
  • Method square uses a return statement because it returns a value
  • Method main does not return a value
    • Return statement is optional if no value is returned
    • Return jump occurs automatically at the end of the method

Exiting Early

  • Sometimes do not want to execute all the code in a method
  • Use return statement to stop execution and return immediately

3.1.6: Local Variables and Scope

  • Scope determines where you can access a variable
  • Variables defined in methods can only be accessed within that method
  • Local variables and method parameters can only be accessed within their block
  • Blocks begin at an opening brace ({) and end at a closing brace (})
  • Variables declared inside a block are known only inside that block
  • When the block finishes executing, local variables disappear
  • References to local variables outside their block cause a compile error

For Example

  • Will the following code compile?
public class Scope {
    public static void main(String[] args) {
        for (int count = 0; count < 5; ++count) {
            System.out.println(count);
        }
        System.out.println(count); //cannot resolve symbol
    }
}
  • How can one access variables outside of a block?
  • How can one access the same variables in different methods?

3.1.7: Overloading Methods

  • Can have several methods with the same name in a class
  • Must have a different parameter list (signature) for each method
    • Number of parameters
    • Parameter types
    • Order of parameters
  • Return type is not part of the signature
    • Compiler cannot distinguish between two methods with the same name and signature

For Example

    class SquareTypes {
        public static void main(String[] args) {
            System.out.println(square(5));
            System.out.println(square(6.5));
        }
    
        static int square(int x) {
            System.out.println("Using int type");
            return x * x;
        }
    
        static double square(double x) {
            System.out.println("Using double type");
            return x * x;
        }
    }
    
  • First call to square uses the method with an int signature
  • Second call uses the method with a double signature
  • Using int type
    25
    Using double type
    42.25
    

Exercise 3.1

Take one minute to prepare an answer the following questions.

  1. Which of the following code fragments are valid method declarations?
    1. methodA() { /*...*/ }
    2. void methodB { /*...*/ }
    3. void methodC() { /*...*/ }
    4. void methodD(void) { /*...*/ }

3.2: Arrays

Objectives

At the end of the lesson the student will be able to:

  • Declare arrays in Java
  • Initialize arrays
  • Use arrays with loops
  • Test array equality

3.2.1: About Arrays

Array: a single name for a collection of identically-typed data values

  • Variables store a single value at some location in memory
  • In contrast, arrays store a set of related values
  • #  vs.  ########
  • Arrays are a type of data structure
  • -- a way to organize data
  • Individual values in an array are called items or elements
  • Entire array referred to by a single identifier
  • Each element uniquely identified by an index number

For Example

  • One-dimensional array is like single row of data in spreadsheet or table
  • a[0] a[1] a[2] a[3] a[4]
    12 15 -1 9 14

  • Top row shows the indices for an array named "a"
  • Individual items are referenced by the index (a.k.a. subscript)
  • All the values are of the same type: int
  • Array length is 5

When to Use Arrays

  • Use arrays for storing data which must be accessed in any order
  • Arrays are a natural fit for loops, especially for loops

3.2.2: Declaring and Allocating Arrays

  • Declaration syntax:
  • DataType[] name;
    or
    DataType name[];
    
  • Arrays are objects and are allocated dynamically with the operator: new
  • Declaration and initialization syntax:
  • DataType[] name = new DataType[length];
    or
    DataType name[] = new DataType[length];
    
  • Once created, cannot change the number of elements
  • For Example

    int[] a;
    a = new int[5];
    
  • Equivalent to:
  • int[] a = new int[5];
    
  • Equivalent to:
  • int a[] = new int[5];
    
  • How many array elements in the above examples?

3.2.3: Initializing Array Values

Reference Types

  • Arrays assignments are different than for primitive types
  • Arrays names are reference types because arrays are objects in Java
  • For instance:
  • double[] prices;
    prices = new double[6];
    
  • First line declares a reference variable of type array-of-doubles
  • Second line creates an array object in memory and assigns the location to the prices reference variable

Default Values

  • Note that the array of doubles has 6 values of 0.0 stored
  • Uninitialized array elements assigned default values:
    • Integer (byte, short, int, long): 0
    • Floating-point (float, double): 0.0
    • Character (char): '\u0000'
    • Boolean: false
    • Objects: null

Static Initialization

  • Array elements can be initialized in the declaration statement
    • Called static initialization
    • Use a comma-separated list in braces
  • Length of an array automatically determined from the initializer list
  • For Example

    int[] a = {12, 15, -1, 9, 14};
    
  • Produces the following array:
  • a[0] a[1] a[2] a[3] a[4]
    12 15 -1 9 14

Initializing Array Values in a Loop

  • A for loop is commonly used to initialize array elements
  • For example:
  • int[] a = new int[10];
    for (int i = 0; i < a.length; i++)
        a[i] = 0;
    
  • Note that the loop counter and array index counts from 0 to length - 1

3.2.4: Using Arrays

  • Array elements referenced by the array name and index
  • Use the array operator [] to specify the index
  • Index must be an integer expression
  • class WeekDays {
        public static void main(String[] args) {
            String[] day = {"Sunday", "Monday",
                "Tuesday", "Wednesday", "Thursday",
                "Friday", "Saturday"};
            for (int x = 0; x < day.length; x++) {
                System.out.println(day[x]);
            }
        }
    }
    
  • Trying to use an index less than 0 or more than length - 1 causes an error
  • ArrayIndexOutOfBoundsException
  • Array elements can be used just like any other variable
  • Can assign values, access values and use in expressions
  • Textbook has several common examples in chapter 7

3.2.5: Arrays of Classes

  • Any type can be made into an array, including class types
  • In the following, array elements are objects (i.e. type String)
  • Can call methods of the class references contained in each array element
  • For instance, length() is a method of the String class
  • class WeekDayLengths {
        public static void main(String[] args) {
            String[] weekday = {"Sunday", "Monday",
                "Tuesday", "Wednesday", "Thursday",
                "Friday", "Saturday"};
            for (int x = 0; x < weekday.length; x++) {
                System.out.print(weekday[x]);
                System.out.print(" has ");
                System.out.print(weekday[x].length());
                System.out.println(" letters.");
            }
        }
    }
    

    Notes on the Code

  • Can use an array of classes like other arrays
  • Can access and use each individual array element
  • System.out.print(weekday[x]);
    
  • Can call a method on each array element
  • System.out.println(weekday[x].length());
    

3.2.6: Testing Array Equality

Using == With Array Names

  • Remember that arrays are objects
  • Thus, array variables are reference types
  • Tests using == checks if the memory addresses are the same
  • if (a == b)
    
  • For example, what does the following code print?
  • public class ArrayEq {
        public static void main(String[] args) {
            int[] a = {1, 2, 3};
            int[] b = {1, 2, 3};
            if (a == b)
               System.out.println("a == b");
            else
                System.out.println("a != b");
        }
    }
    
  • Both arrays have the same elements
  • However, they are stored at different locations in memory
  • Thus, they do not have the same memory address

Testing Array Elements for Equality

  • To test array elements for equality, need to check each element
  • Define an equals method that returns true if and only if all the array elements are equal
  • Arrays must also be the same length
  • Updating our original code:
  • public class ArrayEquals {
        public static void main(String[] args) {
            int[] a = {1, 2, 3};
            int[] b = {1, 2, 3};
            if (a == b)
               System.out.println("a == b");
            else
                System.out.println("a != b");
            if (equals(a, b))
                System.out.println("a equals b: ");
            else
                System.out.println("a not equal to b");
        }
    
        public static boolean equals(int[] a, int[] b) {
            boolean match = true; //tentatively
            if (a.length != b.length)
                match = false;
            else {
                for (int i = 0; i < a.length; i++) {
                    if (a[i] != b[i])
                        match = false;
                }
            }
            return match;
        }
    }
    

Exercise 3.2

Take one minute to prepare an answer the following questions.

  1. Is it possible to create arrays of length zero?
  2. Given the following declaration, which statement is valid?
  3. int[] array = new int[5];
    
    1. System.out.print(array[].length);
    2. System.out.print(array.length());
    3. System.out.print(array[].length());
    4. System.out.print(array.length);
    5. System.out.print(array.size);

3.3: Arrays and Methods

Objectives

At the end of the lesson the student will be able to:

  • Pass array arguments
  • Use arrays in methods
  • Return arrays from methods
  • Obtain values passed to the main method

3.3.1: Arrays as Method Parameters

  • Can use an entire array as an argument to a method
  • When calling the array, use just the array name and no brackets
  • showArray(days);
    
  • Called method has access to the original array
  • Following example shows the use of an array in a method:
  • Do not know the length of the array that will be passed
  • Length of the array passed can be different for each method call
  • So use the length variable inside the method body
  • public static void showArray(String[] a) {
       for (int i = 0; i < a.length; i++)
          System.out.println(a[i]);
    }
    

    Notes on the Code:

    a.length;
    
  • Uses the length variable to control the loop
  • Allows different size arrays and avoids:
  • ArrayIndexOutOfBoundsExceptions
    
  • What would we change to overload the showArray method for another array type?

3.3.2: Changing Array Elements in Methods

  • All types in Java are passed-by-value (a.k.a. call-by-value)
  • When method is called, value of each argument is copied to its corresponding parameter
  • Method only gets a copy of the variable's value
  • Variables used as arguments cannot be changed within the method
  • However, arrays are objects and a variable contains a reference value
  • Thus, the address of the array is passed to the method
  • Any action taken on the parameter is actually taken on the original object
  • Original argument is not protected for class types
  • Thus array elements can be changed in methods

For example:
public class ArrayMod {
    public static void main(String[] args) {
        int[] array = {1, 2, 3};
        System.out.println("Original values:");
        for (int i = 0; i < array.length; i++)
            System.out.println(array[i]);
        changeLastSign(array);
        System.out.println("Final values:");
        for (int i = 0; i < array.length; i++)
            System.out.println(array[i]);
    }

    public static void changeLastSign(int[] a) {
        if (a.length > 0) {
            a[a.length - 1] = -a[a.length - 1];
        }
    }
}

3.3.3: Returning an Array

  • Methods can return an array reference
  • Local array name just another name for the original array
  • For example:
  • public class ArrayReturn {
        public static void main(String arg[]) {
            char[] c;
            c = vowels();
            for(int i = 0; i < c.length; i++)
                System.out.println(c[i]);
        }
    
        public static char[] vowels() {
            char[] newArray = new char[5];
            newArray[0] = 'a';
            newArray[1] = 'e';
            newArray[2] = 'i';
            newArray[3] = 'o';
            newArray[4] = 'u';
            return newArray;
        }
    }
    

3.3.4: Method main Arguments

    public static void main(String[] args) {
    
  • Recall that every Java application must have a method called main
    • Applications begin executing at main method
  • Notice that the parameter args is an array of Strings
  • Arguments are passed to the program by the operating system
  • All words after the class name passed in the args array
  • java EchoArgs Hi Mom!
    
  • args is a parameter of type String[]
  • Arguments are passed by the O/S when calling the program
  • Name args is a convention -- can be named anything
  • Number of parameters can be determined from the length field of args

For Example

    class EchoArgs {
        public static void main(String[] args) {
            for (int i = 0; i < args.length; i++) {
                System.out.print("Arg " + i + ": ");
                System.out.println(args[i]);
            }
        }
    }
    
  • From the command line:
  • >java EchoArgs Hi Mom!
    Arg 0: Hi
    Arg 1: Mom!
    

3.3.5: Summary

  • Can pass an array to a method
  • Can change the array element within a method body
    • Because arrays are reference types
    • Location of the array passed to the method
    • When an element is accessed, the original location is used
  • A method may return an array
  • Operating system sends arguments to the String[] parameter of method main
  • Can access these elements like any other String[]

Exercise 3.3

Take one minute to prepare an answer the following question:

  1. What is wrong with the following method definition?
  2. public void doubleSize(int[] a) {
        a = new int[a.length * 2];
    }
    
    1. An array length must be a literal integer and cannot be created from a calculated expression.
    2. The length of the array a is unknown when declaring the new array.
    3. Parameter a already has an array assigned and you cannot assign a new value to parameter a.
    4. The parameter a goes out of scope when the method returns.

Wrap Up

Home | WebCT | Announcements | Schedule | Expectations | Syllabus
Help | FAQ's | HowTo's | Links

Last Updated: September 17 2003 @16:39:20