Welcome to Lesson 17!

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 for loops with arrays?

1. Lesson 16 Practice Exam Questions

Q1: Write a proper Javadoc comment for the below method from last class

  • Name: displayPrice
    • takes in one double parameter for a price
    • Prints the price to the console with a dollar sign and to two decimal places
    • returns nothing

    Q2: Write the below method:
    • Name: displayPrice
      • takes in one double parameter for a price
      • Prints the price to the console with a dollar sign and to two decimal places
      • returns nothing

    Q3: Now call the method using the starter code below:

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    double number;
    System.out.print("Enter the price: ");
    number = input.nextDouble();
    System.out.print("The formatted price is: ");
    //call the method here!

    2. 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 Elements

    • 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 ints
      • 0.0 for doubles
      • null for Strings

    Accessing Array Elements

    • 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 = 
    • 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:
    • 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}

    Array Length

    • We can always access the length of an array using .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

    * Array Example
    * @author Jennifer Parrish
    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 17.1: My First Array (10pts)

    • Open a new Java project in Eclipse and save it as Arrays
    • Inside main(), add a statement to define an array named names that is suitable for holding a list of six (6) names.
    • Compile your code to make sure it has correct syntax.
      • If you have problems, please post on Piazza.
    • Assign values to the first 3 array elements by inventing some names, like so:
      names[0] = "George Washington";
    • Next, place a print statement below these 3 assignment statements:
    System.out.println("The first 3 names:");
    • Then, add a for-loop to display all three array values.
    • Next, we are going to ask the user to enter the final 3 names to store in the array.
    • Declare a Scanner variable at the top of your program.
    • Add a second for loop to read in the next 3 names from the user input into the array:
    for (int i = ???; i < array.????; i++) {
        System.out.print("Enter name " + (i + 1) + ": ");
        array[i] = ???;
    • Write a last for loop to display all the names in the array.
    System.out.println("\nThe 6 names are: ");
    //write your for loop here
    • When you are finished, run your code and make sure that you are getting output similar to the following (except the names might differ):
    The first 3 names:
    George Washington
    John Adams
    Thomas Jefferson

    Enter name 4: Grace Hopper
    Enter name 5: Ada Lovelace
    Enter name 6: Hedy Lamarr

    The 6 names are:
    George Washington
    John Adams
    Thomas Jefferson
    Grace Hopper
    Ada Lovelace
    Hedy Lamarr
    • When your program is working properly, upload your source code to Canvas.

    Wrap Up

    • Declare an array called pets, and assign it the values "dog", "cat", "rabbit", "bird" in TWO ways (static and not static)


    • Write a for loop to display the pets array to the console

    Upcoming Assignments

    • Activity 17.1 due Thursday at 11:59pm
    • Assignment 16 due Friday at 11:59pm
    • Assignment 17 due next Tuesday at 11:59pm
    • Quiz 8 due Friday at 11:59pm

    ~Have a Great Weekend!~