Computer Science 225
Advanced Programming

Spring 2017, Siena College

FillArray BlueJ Project

Click here to download a BlueJ project for FillArray.


FillArray Source Code

The Java source code for FillArray is below. Click on a file name to download it.


FillArray.java

/*
 * Example FillArray: using the Arrays class from the Java API
 *
 * Jim Teresco, Siena College, Computer Science 225, Spring 2017
 *
 * $Id: templateapp.java 2975 2016-08-30 02:35:29Z terescoj $
 */

// need an import if we want to use the standard Arrays API
import java.util.Arrays;

public class FillArray {

    /**
    Print the contents of an array of int in a readable format

    @param array the array of int to print
     */     
    public static void printArray(int array[]) {

        System.out.print("{ ");
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            if (i < array.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println(" }");
    }

    public static void main(String args[]) 
    {
        // construct and print an array
        int a[] = new int[10];

        // note the default values: all zero
        System.out.println("Array a after construction:");
        printArray(a);

        // fill the array using a very familiar for loop
        for (int i = 0; i < a.length; i++) {
            a[i] = 10;
        }
        System.out.println("Array a after filling with 10s using a for loop:");
        printArray(a);

        // who has time for a for loop, we have Arrays.fill!        
        Arrays.fill(a, 20);
        System.out.println("Array a after filling with 20s using Arrays.fill:");
        printArray(a);
    }
}