Welcome to Lesson 19!


Learning Objectives
By the end of today's class, you should know...
  • How do you declare an array?
  • How do you assign it values?
  • What is static initialization?
  • How do you use arrays as method parameters?
  • How do you return an array from a method?

Announcements

  • Lab 9 for Friday
  • Quiz 8 for Friday


Review Activity

With a partner, answer the following questions:

  • Write the below method:
    • Name: makes10
    • Takes in 2 integer parameters
    • Returns true if one if them is 10, or their sum is 10
  • Write the Javadoc comment for the above method
  • Given the starter code below, call the method:
public static void main(String[] args) {
    boolean result;
    Scanner input = new Scanner(System.in);
   
    System.out.println("Enter a number: ");
    int a = input.nextInt();

    System.out.println("Enter a second number: ");
    int b = input.nextInt();

    //call the method here!


    System.out.println("Makes 10: " + result);
    input.close();
}
  • Write a method called formatPrice:
    • The method takes in one double parameter
    • It displays the double to the console in the format $X.XX
    • It returns nothing
  • Given the starter code below, call the method:
    public static void main(String[] args) {
       
        Scanner input = new Scanner(System.in);
       
        System.out.println("Enter a price: ");
        double price = input.nextDouble();

       
        //call the method here!


        input.close();
    }


Arrays

Using Lists to Store Data in Computer Science

  • We are all familiar with lists.
  • We use lists all the time for things like grocery shopping, e.g.:
    • Bread
    • Kale
    • Chocolate
  • Or, keeping track of our assignments:
    • Physics exam Wednesday.
    • Do Calc homework tonight.
    • Read short story for English.

Defining Arrays

  • An array is a collection of data items all of the same type
  • You declare an array like this:
    dataType[] variableName = new dataType[length];
    
  • You can also declare an array like this:
    dataType variableName[] = new dataType[length];
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • length: the number of data items the array can hold
  • For example, the following is the declaration of an array named scores that holds 10 values of type int:
    int[] scores = new int[10];
  • When a program executes this statement, it creates 10 contiguous slots in memory like this:
    scores = 
     
     
     
     
     
     
     
     
     
     
  • Each of the memory slots can hold one data value
  • We can have arrays of any type:
double[] anArrayOfDoubles;
boolean anArrayOfBooleans[];
char[] anArrayOfChars;
String anArrayOfStrings[];
  • Once you define the length of an array, it cannot change length later in the program.
  • When defining an array, you must guess the maximum number of elements you need to store:
    int[] scores = new int[100];
    
  • If you need to know the length of an array, you can always use the length property (more on this below):
          System.out.println(scores.length) //Will print out 100

Initializing Array Items

  • We specify which slot of an array to access with the [] operator:
    scores[4] = 98;
  • The indexes of arrays are numbered starting at 0
  • We can assign a value to an array element any time after it is declared:
    scores[0] = 90;
    scores[1] = 95;
    scores[2] = 87;
    scores[3] = 89;
    scores[4] = 98;
    
  • We can also initialize array elements in the declaration statement:
    • Called static initialization
    • We use a comma-separated list inside curly-braces
  • For example:
    int[] scores = { 90, 95, 87, 89, 98 };
    
  • This produces the same array as in the previous example
  • The compiler computes the size automatically by counting the items in the list
Default Array Values
  • When an array is declared, Java automatically assigns each element a default value: false for booleans, 0 for numerical types

Accessing Array Items

  • To access the slots in an array, we must specify which slot to use with the [] operator
  • For instance:
    scores[4] = 98;
  • The number inside the brackets is called an index or subscript
  • In Java, the slots of an array are numbered starting at 0, as shown below:
    scores = 
     
     
     
     
    98
     
     
     
     
     
    [0]
    [1]
    [2]
    [3]
    [4]
    [5]
    [6]
    [7]
    [8]
    [9]
  • Thus, assignment to the slot with an index of 4 is put into the fifth slot

Using Slots

  • We declared our example array with a data type of int:
    int[] scores = new int[10];
  • Because scores is an array containing int values, we can use a slot, such as scores[4], just like any variable of type int:
    scores[4]++;
    System.out.println(scores[4]);
    
  • This includes using a slot as an argument to a method with a parameter of the same type:
    public static void myMethod(int singleScore){//method body}
    ...
    myMethod(scores[4]); 

Array Length

  • We can always access the length of an array using .length

System.out.println(scores.length);

  • Note that the length of the array is always one more than its last index

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

Image source.

Using Arrays to Collect Data Items

  • Note that the index of an array can be any integer value
  • Thus, we can use an integer variable for the index
  • We can use an integer variable with a loop to read data into the array
  • Also, we can display the contents of an array using a loop
  • The following program shows an example of collecting and displaying data items


Example Program Using Arrays to Collect and Display Data Items



/**
*
* @author parrishj
*/
import java.util.Scanner;
public class Arrays {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int[] scores = new int[5];
System.out.println("Array elements initialized to 0:");
for (int i =0; i <scores.length; i++){
System.out.println("Index " + i + ": " + scores[i]);
}
System.out.println("\nEnter " + scores.length + " scores:");
for (int i =0; i <scores.length; i++){
scores[i] = input.nextInt();
}
System.out.println("\nYou entered:");
for (int i =0; i <scores.length; i++){
System.out.println("Score " + i + ": " + scores[i]);
}
}

}

Activity 19.1: My First Array (10pts)

  • Open a new Java project in Eclipse and save it as Arrays, and then compile and run the starter program to make sure you copied it correctly.

    /**
    *
    * @author
    */
    import java.util.Scanner;
    public class Arrays {
    public static void main(String[] args) {


    }

    }

  • Inside main(), add a statement to define an array named names that is suitable for holding a list of three (3) names.
  • Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  • Assign values to each of the array elements like:
    names[0] = "Abel Ableson";
    
  • Add a for-loop to display all three array values.
  • Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  • When you are finished, upload your source code to Canvas.


Arrays Continued

Arrays and Methods

  • When writing a method with an array parameter, we place an empty [] after the datatype or parameter name:
    public static void print(int values[]); //will work for an array of any size
    
  • When we call the method, we do NOT include the []:
    print(data); // name of the array is data
    
  • Instead, we pass in the name of the array.

Example program passing an array to a method

public static void print(int values[]){
        for (int i = 0; i < values.length; i++)
            System.out.println(values[i]);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] scores = {90, 89, 76, 55, 91};
        print(scores);
     
    }

  • Unlike other parameters, you can pass the array into the method and then alter the array inside of the method without needing to return a new array.
  • For example, what do you think will be the result of running the following program?
import java.util.Scanner;
public class Arrays {
   
    public static void assignValues(int values[]){
        for (int i = 0; i < values.length; i++){
            values[i] = i;
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[]  arr = new int[10];
        assignValues(arr);
     
        for (int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }
       

  • It is also possible to return an array from a method.
  • For example:



/**
 *
 * @author Jennifer Parrish
 */
import java.util.Scanner;
public class Arrays {
   
    public static int[] assignValues(int values[]){
        for (int i = 0; i < values.length; i++){
            values[i] = i;
        }
        return values;
    }



    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[]  arr = new int[10];
        arr = assignValues(arr);

        System.out.println("After filling the array:");
        for (int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }

       
    }
 
}



Activity 19.2: Exploring Arrays (10 pts)
  • In this exercise we explore declaring, allocating and assigning values to arrays containing lists of data
  • Create a Java project called Arr
  • Add the following method to the code:
    public static void print(int values[]) {
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + " ");
        }
    }
    
  • Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  • Declare and initialize an array for a list of 10 integer scores:
    int scores[] = {90, 91, 92, 93, 94, 95, 96, 97, 98, 99};
    
  • After declaring and initializing the array, call the print() method using the code:
    System.out.println("Integer exam scores:");
    print(scores);
  • Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like this:
    Integer exam scores:
    90 91 92 93 94 95 96 97 98 99
    
  • Next, write a method, named addExtraCredit. This method uses a for loop to add 5 points to each exam score in the scores array.
  • The method should have the following signature:      

public static void addExtraCredit(int values[]) {
    //Write the body of the method here
//Note: Do not print anything in this method
//No System.out.print statement(s) go here
}

  • Next, call this method, passing in the scores array.
  • Then, call the print method again to display the values, along with the message After adding extra credit:
  • Note: Do NOT print inside of the addExtraCredit method. Call the print method to print the array. AddExtraCredit should only add extra credit to the scores. It should not print anything inside the body of the method.

  • Compile and run the program to make sure you made the changes correctly. When you run the program, the new output should look like this:
    After adding extra credit:
    95 96 97 98 99 100 101 102 103 104
    
  • Declare and initialize an array of double values holding rainfall values (in inches) 23.4, 16.4, 18.9, and 52.7
  • Write another print() method with one parameter for the array of double values.
  • After declaring and initializing the array, call the print() method.
  • Note that you can re-use the name print for this second method. The compiler will know they are different methods because the parameters are different. This is called method overloading.
  • Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like this:

Integer exam scores:
90 91 92 93 94 95 96 97 98 99
After adding extra credit:
95 96 97 98 99 100 101 102 103 104
Double rainfall in inches
23.4 16.4 18.9 52.7

  • Declare and allocate an array of char values and assign it the vowels a, e, i, o and u.
  • After declaring and initializing the array, write another print method to display it. Again, this method should be named print(). Then, call this method in main.
  • Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like this:
  • Integer exam scores:
    90 91 92 93 94 95 96 97 98 99
    After adding extra credit:
    95 96 97 98 99 100 101 102 103 104
    Double rainfall in inches
    23.4 16.4 18.9 52.7
    Char vowels
    a e i o u
    

  • When your program gives the above output, upload your program to Canvas.

Wrap Up
  • With a partner, answer the questions from today's learning objectives


Upcoming Assignments


~See You Tuesday!~