Intro into Arrays

  • An array is a data structure used to implement a collection (list) of primitive or object reference data.

  • An element is a single value in the array

  • The **index** of an element is the position of the element in the array

    • In java, the first element of an array is at index 0.
  • The length of an array is the number of elements in the array.

    • length is a public final data member of an array

      • Since length is public, we can access it in any class!

      • Since length is final we cannot change an array’s length after it has been created

    • In Java, the last element of an array named list is at index list.length -1

A look into list Memory

int [] listOne = new int[5];

This will allocate a space in memory for 5 integers.

ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

Using the keyword new uses the default values for the data type. The default values are as follows:

Data Type Default Value
byte (byte) 0
short (short) 0
int 0
double 0.0
boolean false
char ‘\u0000’

What do we do if we want to insert a value into the array?

listOne[0] = 5;

Gives us the following array:

ARRAY: [0, 0, 0, 0, 0]
INDEX:  0  1  2  3  4

What if we want to initialize our own values? We can use an initializer list!

int [] listTwo = {1, 2, 3, 4, 5};

Gives us the following array:

ARRAY: [1, 2, 3, 4, 5]
INDEX:  0  1  2  3  4

If we try to access an index outside of the range of existing indexes, we will get an error. But why? Remember the basis of all programming languages is memory. Because we are trying to access a location in memory that does not exist, java will throw an error (ArrayIndexOutOfBoundsException).

How do we print the array? Directly printing the array will not work, it just prints the value of the array in memory. We need to iterate through the array and print each value individually!

/* lets take a look at the above */

int [] listOne = new int[5]; // Our list looks like [0, 0, 0, 0, 0] use new key word so that it does not generate random numbers

listOne[2] = 33; // Our list looks like [0, 0, 33, 0, 0]
listOne[3] = listOne[2] * 3; // Our list looks like [0, 0, 33, 99, 0]

try {
    listOne[5] = 13; // This will return an error
} catch (Exception e) {
    System.out.println("Error at listOne[5] = 13");
    System.out.println("ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!");
}


System.out.println(listOne); // THIS DOES NOT PRINT THE LIST!! It prints the value in memory
System.out.println(listOne[4]); // This will actually print the vaules in the array
Error at listOne[5] = 13
ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!
[I@79845b3c
0

Popcorn Hacks!

Write code to print out every element of listOne the following

/* popcorn hacks go here */

for(int i = 0; i <= listOne.length-1; i++){
    System.out.println((listOne[i]));
}

System.out.println(Arrays.toString(listOne));
0
0
33
99
0
[0, 0, 33, 99, 0]

Reference elements

Lists can be made up of elements other than the default data types! We can make lists of objects, or even lists of lists! Lets say I have a class Student and I want to make a list of all students in the class. I can do this by creating a list of Student objects.

Student [] classList;
classList new Student [3];

Keep in mind, however, that the list won’t be generated with any students in it. They are initialized to null by default, and We need to create the students and then add them to the list ourselves.

classList[0] = new Student("Bob", 12, 3.5);
classList[1] = new Student("John", 11, 4.0);
classList[2] = new Student("Steve", 10, 3.75);

Popcorn hacks!

Use a class that you have already created and create a list of objects of that class. Then, iterate through the list and print out each object using: 1) a for loop 2) a while loop

public class Animal {

    private String animal;
    private int age;
    private int weight;

    public Animal(String animal, int age, int weight){
        this.animal = animal;
        this.age = age;
        this.weight = weight;

    }

    public String toString(){
        return "animal= " + animal + ", age=" + age + ", weight=" + weight;
    }
}
/* Popcorn hacks go here */

public class Main {
    public static void main(String [] args){
        Animal[] classList = new Animal[3];
        classList[0] = new Animal("Dog", 5, 100);
        classList[1] = new Animal("Cat", 2, 30);
        classList[2] = new Animal("Horse", 6, 200);

        for(Animal animal : classList){
            System.out.println(animal);
        }
    }
}

Main.main(null);
animal= Dog, age=5, weight=100
animal= Cat, age=2, weight=30
animal= Horse, age=6, weight=200

Enhanced for loops

The enhanced for loop is also called a for-each loop. Unlike a “traditional” indexed for loop with three parts separated by semicolons, there are only two parts to the enhanced for loop header and they are separated by a colon.

The first half of an enhanced for loop signature is the type of name for the variable that is a copy of the value stored in the structure. Next a colon separates the variable section from the data structure being traversed with the loop.

Inside the body of the loop you are able to access the value stored in the variable. A key point to remember is that you are unable to assign into the variable defined in the header (the signature)

You also do not have access to the indices of the array or subscript notation when using the enhanced for loop.

These loops have a structure similar to the one shown below:

for (type declaration : structure )
{
    // statement one;
    // statement two;
    // ...
}

Popcorn Hacks!

Create an array, then use a enhanced for loop to print out each element of the array.

/* Popcorn hacks go here */
int [] grades = {61, 68, 79, 86, 93, 99};

for(int grade: grades){
    System.out.println(grade);
}
61
68
79
86
93
99

Min maxing

It is a common task to determine what the largest or smallest value stored is inside an array. in order to do this, we need a method that can ake a parameter of an array of primitive values (int or double) and return the item that is at the appropriate extreme.

Inside the method of a local variable is needed to store the current max of min value that will be compared against all the values in the array. you can assign the current value to be either the opposite extreme or the first item you would be looking at.

You can use either a standard for loop or an enhanced for loop to determine the max or min. Assign the temporary variable a starting value based on what extreme you are searching for.

Inside the for loop, compare the current value against the local variable, if the current value is better, assign it to the temporary variable. When the loop is over, the local variable will contain the approximate value and is still available and within scope and can be returned from the method.

Popcorn Hacks!

Create two lists: one of ints and one of doubles. Use both a standard for loop and an enhanced for loop to find the max and min of each list.

/* Popcorn hacks go here! */

public class MinMax {

    public static void main(String [] args){

        int [] scores = { 93, 72, 84, 98, 62, 100, 78};
        double [] prices = {31.32, 18.73, 20.78, 14.5, 26.54, 39.76, 35.81};

        int max1 = scores[0];
        for(int i = 0; i < scores.length; i++){ // standard for loop
            if(max1 < scores[i]){
                max1 = scores[i];
            }
        }
        System.out.println("The maximum value for the array of scores is " + max1);

        int min1 = scores[0];
        for(int score : scores){ // enhanced for loop
            if(min1 > score){
                min1 = score;
            }
        }
        System.out.println("The minimum value for the array of scores is " + min1);
        

        double max2 = prices[0];
        for(double price : prices){ // enhanced for loop
            if(max2 < price){
                max2 = price;
            }
        }
        System.out.println("The maximum value for the array of prices is " + max2);

        double min2 = prices[0];
        for(int j = 0; j < prices.length; j++){ // standard for loop
            if(min2 > scores[j]){
                min2 = scores[j];
            }
        }

        System.out.println("The minimum value for the array of prices is " + min2);

    
    }

}
MinMax.main(null);


The maximum value for the array of scores is 100
The minimum value for the array of scores is 62
The maximum value for the array of prices is 39.76
The minimum value for the array of prices is 31.32

Extra

I also created a sorting algorithm in Java that sorts both of the lists in the previous code segment from least to greatest.

public class Sort {

    public static int [] sortInt(int[] intList) { // sorting for array of ints
        int length = intList.length;
    
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length - i - 1; j++) {
                if (intList[j] > intList[j + 1]) {
                    int temp = intList[j];
                    intList[j] = intList[j+1];
                    intList[j + 1] = temp;
                }
            }
        }
    
        return intList;
    }

    public static double [] sortDouble(double[] doubleList) { // sorting for array of doubles
        int length = doubleList.length;
    
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length - i - 1; j++) {
                if (doubleList[j] > doubleList[j + 1]) {
                    double temp = doubleList[j];
                    doubleList[j] = doubleList[j+1];
                    doubleList[j + 1] = temp;
                }
            }
        }
    
        return doubleList;
    }


}
int [] scores = {93, 72, 84, 98, 62, 100, 78};
double [] prices = {31.32, 18.73, 20.78, 14.5, 26.54, 39.76, 35.81};

System.out.println("Unsorted Scores List: " + Arrays.toString(scores));
System.out.println("Unsorted Prices List: " + Arrays.toString(prices));

Sort.sortInt(scores);
Sort.sortDouble(prices);

System.out.println("Sorted Scores List: " + Arrays.toString(scores));
System.out.println("Sorted Prices List: " + Arrays.toString(prices));

Unsorted Scores List: [93, 72, 84, 98, 62, 100, 78]
Unsorted Prices List: [31.32, 18.73, 20.78, 14.5, 26.54, 39.76, 35.81]


Sorted Scores List: [62, 72, 78, 84, 93, 98, 100]
Sorted Prices List: [14.5, 18.73, 20.78, 26.54, 31.32, 35.81, 39.76]

Given an input of N integers, find A, the maximum, B, the minimum, and C the median.

Print the following in this order:

A + B + C

A - B - C

(A + B) * C

Sample data:

INPUT: 5 1 2 3 4 5

OUTPUT: 9 1 18

INPUT: 9 2 4 6 8 10 10 12 14 16

OUTPUT: 28 6 180

public class Cool {

    public static int min(int [] array){

        int min = array[0];
        for(int i = 0; i < array.length; i++){
            if(min > array[i]){
                min = array[i];
            }
            
        }

        return min;
    }

    public static int max(int [] array){
        int max = array[0];
        for(int i = 0; i < array.length; i++){
            if(max < array[i]){
                max = array[i];
            }
        }

        return max;
    }

    public static int median(int [] array){
        int median;
        Arrays.sort(array);

        if(array.length % 2 != 0){
            median = array[array.length/2];

        } else {
            median = ((array[array.length/2] + array[array.length/2-1])/2);
        }

        return median;

    }

    
}
public class Main {
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number of digits you would like in the array: ");
        int n = sc.nextInt();

        System.out.printf("Enter %d integers!%n",n);

        int [] nums = new int[n];

        for(int i = 0; i < n; i++){
            nums[i] = sc.nextInt();
        }

        System.out.println("List of your numbers: " + Arrays.toString(nums));
        System.out.println(Cool.max(nums)+Cool.min(nums)+Cool.median(nums));
        System.out.println(Cool.max(nums)-Cool.min(nums)-Cool.median(nums));
        System.out.println((Cool.max(nums)+Cool.min(nums))*Cool.median(nums));

    }
}

Main.main(null);
Enter the number of digits you would like in the array: 


Enter 5 integers!
List of your numbers: [3, 16, 8, 5, 11]
27
5
152

For extra, create your own fun program using an array

This program uses user input in order to create an array of numbers of size n. It then creates two other lists by filtering out all of the odd and even numbers so that there is a separate list of even numbers and a separate list of odd numbers.

public class Extra {

    public int [] oddCheck(int [] nums){
        int oddCount = 0;
        for(int num : nums){
            if(num % 2 != 0){
                oddCount++;
            }
        }

        int [] oddNums = new int[oddCount];

        int i = 0;
        for(int num : nums){
            if(num % 2 != 0){
                oddNums[i] = num;
                i++;
            }
        }

        return oddNums;
    }


    public int [] evenCheck(int [] nums){
        int evenCount = 0;
        for(int num : nums){
            if(num % 2 == 0){
                evenCount++;
            }
        }

        int [] evenNums = new int[evenCount];

        int j = 0;
        for(int num: nums){
            if(num % 2 == 0){
                evenNums[j] = num;
                j++;
            }
        }

        return evenNums;

    }

    
}
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of digits you would like in the array: ");
int n = sc.nextInt();

System.out.printf("Enter %d integers!%n",n);

int [] numbers = new int[n];

for(int i = 0; i < n; i++){
    numbers[i] = sc.nextInt();
}

Extra extra = new Extra();

System.out.println("Your entire list of numbers: " + Arrays.toString(numbers));

int [] oddNumbers = extra.oddCheck(numbers);
System.out.println("Your entire list of odd numbers: " + Arrays.toString(oddNumbers));

int [] evenNumbers = extra.evenCheck(numbers);
System.out.println("Your entire list of even numbers: " + Arrays.toString(evenNumbers));


Enter the number of digits you would like in the array: 


Enter 5 integers!
Your entire list of numbers: [21, 17, 35, 8, 41]
Your entire list of odd numbers: [21, 17, 35, 41]
Your entire list of even numbers: [8]