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]

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@620c6ceb
0

Popcorn Hacks!

Write code to print out every element of listOne the following

public class ArrayElements {
    public static void main(String[] args) {
        int[] listOne = new int[5];
        listOne[0] = 10;
        listOne[1] = 20;
        listOne[2] = 30;
        listOne[3] = 40;
        listOne[4] = 50;

        System.out.println("printing elements of listOne:");
        for (int i = 0; i < listOne.length; i++) {
            System.out.println(listOne[i]);
        }
    }
}
ArrayElements.main(null)
printing elements of listOne:
10
20
30
40
50

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

import java.util.ArrayList;
import java.util.List;

class Student {
    private String name;
    private int age;
    private double grade;

    public Student(String name, int age, double grade) {
        this.name = name;
        this.age = age;
        this.grade = grade;
    }

    @Override
    public String toString() {
        return "Name: " + name + ", Age: " + age + ", Grade: " + grade;
    }
}

public class StudentListIteration {
    public static void main(String[] args) {
        // Create a list of Student objects
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("Jillian", 16, 99.5));
        studentList.add(new Student("Josh", 16, 92.3));
        studentList.add(new Student("JingJang", 16, 78.9));

        // Iterate through the list using a for loop
        System.out.println("iterating using a for loop:");
        for (int i = 0; i < studentList.size(); i++) {
            System.out.println(studentList.get(i));
        }

        // Iterate through the list using a while loop
        System.out.println("\niterating using a while loop:");
        int index = 0;
        while (index < studentList.size()) {
            System.out.println(studentList.get(index));
            index++;
        }
    }
}
StudentListIteration.main(null)
iterating using a for loop:
Name: Jillian, Age: 16, Grade: 99.5
Name: Josh, Age: 16, Grade: 92.3
Name: JingJang, Age: 16, Grade: 78.9

iterating using a while loop:
Name: Jillian, Age: 16, Grade: 99.5
Name: Josh, Age: 16, Grade: 92.3
Name: JingJang, Age: 16, Grade: 78.9

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.

public class Array {
    public static void main(String[] args) {
        // Create an array of integers
        int[] numbers = {10, 20, 30, 40, 50};

        // Use an enhanced for loop to print each element of the array
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}
Array.main(null)
10
20
30
40
50

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.

import java.util.ArrayList;
import java.util.List;

public class MaxMinFinder {
    public static void main(String[] args) {
        // list of integers
        List<Integer> intList = new ArrayList<>();
        intList.add(10);
        intList.add(5);
        intList.add(20);
        intList.add(15);
        intList.add(30);
        intList.add(25);

        // list of doubles
        List<Double> doubleList = new ArrayList<>();
        doubleList.add(10.5);
        doubleList.add(5.2);
        doubleList.add(20.1);
        doubleList.add(15.7);
        doubleList.add(30.3);
        doubleList.add(25.6);

        // maximum and minimum values in the integer list
        int intMax = intList.get(0);
        int intMin = intList.get(0);

        for (int i = 1; i < intList.size(); i++) {
            int currentValue = intList.get(i);
            if (currentValue > intMax) {
                intMax = currentValue;
            }
            if (currentValue < intMin) {
                intMin = currentValue;
            }
        }

        // maximum and minimum values in the double list
        double doubleMax = doubleList.get(0);
        double doubleMin = doubleList.get(0);

        for (int i = 1; i < doubleList.size(); i++) {
            double currentValue = doubleList.get(i);
            if (currentValue > doubleMax) {
                doubleMax = currentValue;
            }
            if (currentValue < doubleMin) {
                doubleMin = currentValue;
            }
        }

        System.out.println("Integer List - Standard For Loop:");
        System.out.println("Max: " + intMax);
        System.out.println("Min: " + intMin);

        System.out.println("\nDouble List - Standard For Loop:");
        System.out.println("Max: " + doubleMax);
        System.out.println("Min: " + doubleMin);

        double doubleMaxEnhanced = Double.NEGATIVE_INFINITY;
        double doubleMinEnhanced = Double.POSITIVE_INFINITY;

        for (Double value : doubleList) {
            if (value > doubleMaxEnhanced) {
                doubleMaxEnhanced = value;
            }
            if (value < doubleMinEnhanced) {
                doubleMinEnhanced = value;
            }
        }

        System.out.println("\nDouble List - Enhanced For Loop:");
        System.out.println("Max: " + doubleMaxEnhanced);
        System.out.println("Min: " + doubleMinEnhanced);
    }
}
MaxMinFinder.main(null)
Integer List - Standard For Loop:
Max: 30
Min: 5

Double List - Standard For Loop:
Max: 30.3
Min: 5.2

Double List - Enhanced For Loop:
Max: 30.3
Min: 5.2

Hacks (Due 10/22 11:59 PM)

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

For extra, create your own fun program using an array

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

import java.util.Arrays;

public class FindMinMaxMedian {
    public static void main(String[] args) {
        int[] numbers = {10, 5, 20, 15, 30, 25};

        //  maximum (A)
        int max = Arrays.stream(numbers).max().getAsInt();

        //  minimum (B)
        int min = Arrays.stream(numbers).min().getAsInt();

        //  median (C)
        Arrays.sort(numbers);
        int median;
        if (numbers.length % 2 == 0) {
            median = (numbers[numbers.length / 2 - 1] + numbers[numbers.length / 2]) / 2;
        } else {
            median = numbers[numbers.length / 2];
        }

        System.out.println("Maximum (A): " + max);
        System.out.println("Minimum (B): " + min);
        System.out.println("Median (C): " + median);
    }
}
FindMinMaxMedian.main(null)
Maximum (A): 30
Minimum (B): 5
Median (C): 17

Print the following in this order: A + B + C A - B - C (A + B) * C

public class Expressions {
    public static void main(String[] args) {
        int A = 30; // Replace with the actual maximum value
        int B = 5;  // Replace with the actual minimum value
        int C = 20; // Replace with the actual median value

        int result1 = A + B + C;
        int result2 = A - B - C;
        int result3 = (A + B) * C;

        System.out.println("A + B + C: " + result1);
        System.out.println("A - B - C: " + result2);
        System.out.println("(A + B) * C: " + result3);
    }
}
Expressions.main(null)
A + B + C: 55
A - B - C: 5
(A + B) * C: 700
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