Skip to content

Week 10 - Arrays

Arrays

FIRST Let’s Review

What Things do You Need More Help With?

  • Review the what you should know by now section and come up with some questions about topics you are still not clear on.

What You Should Know by Now

  • Input / Output
    • sout, scanner, input streams
  • Comments
    • javadoc
    • single line or multi-line comments
  • Variables
    • Declaration and data-type
    • Assignment
    • Naming conventions
    • Access Modifier
  • Data Types
    • type casting
    • Basic types: int, double, float, long
    • Special types: Strings
    • Object types
  • Operators
    • Arithmetic
    • Assignment
    • Comparison
    • Logical
    • Bitwise
  • Packages and Imports
    • Math
    • Scanner
    • Package VS Class VS Object
  • Conditionals
    • if/else if/else
    • switch
    • ternary
  • Loops
    • While loop
    • For loop
    • do while
    • break / continue
  • Methods
    • Static VS Public: Class accessible VS Object accessible
    • Acessing / Calling a Method: dot notation or .
    • Access Modifier: public, protected, private, determines if can be accessed outside class and inherited and overloaded.
    • Method Parameters: Between ( ), preceeded by Data-Type, follows variable naming conventions
    • Return types (i.e. Value Methods): After access and optional static modifier, is a Data-Type
    • Overloading: Same method name, different parameter signature.
    • Constructors: Same name as class it constructs, always public, no return type.
    • Scope: Containment in brackets: { }
  • Class
    • Naming, File Naming, and Packaging
    • Declaration
    • Attributes / Instance variables

Array Declaration

Method 1 - Long way

1
2
3
4
5
6
7
String[] companies = new String[5];

companies[0] = "Apple";
companies[1] = "Microsoft";
companies[2] = "Oracle";
companies[3] = "VMWare";
companies[4] = "Raspberry Pi Foundation";
Declaration Excercise

Use what you’ve learned to define 2 arrays: * Define an array of the primitive type int that will hold 5 elements and assign the values 10, 9, 8, 7, 6. * Define a Second array of the Object type Integer that will hold 5 elements and assign the values 20, 19, 18, 17, 16.

Declaration Answer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class ArrayDeclaration {
    public static void partOne() {
        final int high = 10, low = 6;

        // Method 1 using procedural programming and a loop to assign values.
        int[] myInt = new int[high - low + 1];
        for (int j=0, i = high; i >= low; j++, i--) {
            myInt[j] = i;
        }
        System.out.println(Arrays.toString(myInt));

        // Alternate method utilizing functional programming paradigm
        myInt = IntStream.rangeClosed(low, high).map(i -> high - i + low).toArray();
        System.out.println(Arrays.toString(myInt));
    }

    public static void partTwo() {
        final int high = 20, low = 16;

        // Method 1 using procedural programming and a loop to assign values.
        Integer[] myInteger = new Integer[high - low + 1];
        for (int j=0, i = high; i >= low; j++, i--) {
            myInteger[j] = i;
        }
        System.out.println(Arrays.toString(myInteger));

        // Alternate method utilizing functional programming paradigm
        myInteger = Stream.iterate(high, i -> i - 1).limit(5).toList().toArray(new Integer[0]);
        System.out.println(Arrays.toString(myInteger));
    }

    public static void main(String[] args) {
        partOne();
        partTwo();
    }
}

Method 2 - Short way

1
String[] companies = {"Apple", "Microsoft", "Oracle", "VMWare","Raspberry Pi Foundation"};

Access the Elements of an Array

1
System.out.println( companies[2] ); // Expected output would be "Oracle"
Access Excercise

Given the Array definition below, how would you swap the values at index 0 and 1?

1
2
3
4
5
6
int[] numbers= new int[5];
numbers[0] = 42;
numbers[1] = 13;
numbers[2] = 12;
numbers[3] = 7;
numbers[4] = 1;

Answer
1
2
3
int helper = numbers[0];
numbers[0] = numbers[1];
numbers[1] = helper;
Swap Excercise

Given your answer above, can you write a generalized swap method that takes two integer arguments representing the indices to swap and swaps them?

Answer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Arrays;

public class ArrayTests {
    public static <T> T[] swapImmutable(T[] arr, int i1, int i2) {
        if (i1 < 0 || i1 >= arr.length || i2 < 0 || i2 >= arr.length) {
            throw new IllegalArgumentException("Invalid index values");
        }

        // Create a copy of the original array to keep it immutable
        T[] newArray = Arrays.copyOf(arr, arr.length);

        // Use the swapOperation to swap the elements
        newArray[i1] = arr[i2];
        newArray[i2] = arr[i1];

        return newArray;
    }

    /**
     * Swaps two indexes of an Object array in a procedural way.
     * @param arr: Passed by reference, so mutable.
     * @param i1: index 1
     * @param i2 index 2
     */
    public static <T> void swap(T[] arr, int i1, int i2) {
        if (i1 < 0 || i1 >= arr.length || i2 < 0 || i2 >= arr.length) {
            throw new IllegalArgumentException("Invalid index values");
        }

        T value = arr[i2];
        arr[i2] = arr[i1];
        arr[i1] = value;
    }

    public static void main(String[] args) {
        String[] myStringArr = new String[] {"Hello", "Java", "Gurus", "Have a nice day!"};
        System.out.println(Arrays.toString(myStringArr));
        ArrayTests.swap(myStringArr, 0, 2);
        System.out.println(Arrays.toString(myStringArr));  // Showing that it is swapped and mutated.
        String[] newArr = ArrayTests.swapImmutable(myStringArr, 0, 2);
        System.out.println(Arrays.toString(myStringArr));  // Showing that is not mutated
        System.out.println(Arrays.toString(newArr));       // Showing that the new array swapped
    }
}

Change Elements of an Array

1
2
companies[2] = "College of the Redwoods";
System.out.println( companies[2] ); // Expected output would be "Ciollege of the Redwoods"

Array Length and Accessing the Last Element

1
String lastElement = companies[companies.length - 1];  // -1 because remember computer scientist start counting at "0"

Array Looping

Basic Loop

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

Enhanced OR foreach Loop

1
2
3
for(String e : companies) {
    System.out.println( e );
}
Looping Exercise

The provided code template includes an array with numbers. Your task is to finish the program so that it prompts the user to input a number for searching within the array. If the array includes the specified number, the program should indicate the index where the number is found. However, if the number is not present in the array, the program should inform the user that the number was not located.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import java.util.Scanner;

public class ArrayLooping {
    public static Scanner s = new Scanner(System.in);

    public static void main(String[] args) {
        int[] numbers = new int[4];
        numbers[0] = 42;
        numbers[1] = 13;
        numbers[2] = 12;
        numbers[3] = 7;
    }
}

Looping Answer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.Scanner;

public class ArrayLooping {
    public static Scanner s = new Scanner(System.in);

    public static <T> int linearSearch(T[] arr, T search) {
        for(int i=0; i < arr.length; i++) {
            if(arr[i].equals(search)) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Integer[] numbers = new Integer[4];
        numbers[0] = 42;
        numbers[1] = 13;
        numbers[2] = 12;
        numbers[3] = 7;

        int numToFind = 13;
        int index = linearSearch(numbers, numToFind);

        if( index != -1 ) {
            System.out.printf("Found %d at %d%n", numToFind, index);
        } else {
            System.out.printf("Failed to find %d%n", numToFind);
        }

        numToFind = 15;
        index = linearSearch(numbers, numToFind);
        if( index != -1 ) {
            System.out.printf("Found %d at %d%n", numToFind, index);
        } else {
            System.out.printf("Failed to find %d%n", numToFind);
        }
    }
}

Multidimensional Arrays

Declaring

1
String[][] myCompanies = { {"Apple", "Microsoft"}, {"Facebook", "Twitter"} };

Accessing

1
System.out.println(myCompanies[1][0]); // Expected output "Facebook"

Looping!

1
2
3
4
5
for (int i = 0; i < myCompanies.length; ++i) {
  for(int j = 0; j < myCompanies[i].length; ++j) {
    System.out.println(myCompanies[i][j]);
  }
}
Last Exercise

Implement a method public static void printInStars(int[] array) in a class named Printer to display rows of stars, with each row having a number of stars determined by the corresponding element in the given array.

Last Answer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Printer {
    public static void printInStarsWithFormat(int[] array) {
        System.out.println("-- The dynamic format and replace method. --");
        for (int value : array) {
            System.out.print(String.format("%" + value + "s%n", "").replace(' ', '*'));
        }

        System.out.println("-- The String repeat char method. --");
        for (int value : array) {
            System.out.printf("%s%n", "*".repeat(value));
        }
    }
    public static void printInStars(int[] array) {
        for (int value : array) {
            for (int i = 0; i < value; i++) {
                System.out.print("*");
            }
            System.out.println(); // Move to the next line after each row of stars
        }
    }

    public static void printInStarsFunctional(int[] array) {
        String stars = IntStream.of(array)
                .mapToObj(count -> "*".repeat(count))
                .collect(Collectors.joining("\n"));

        System.out.println(stars);
    }

    public static void main(String[] args) {
        int[] starCounts = {3, 5, 2, 7, 4};
        System.out.println("Method 1 - Procedural nested loops");
        printInStars(starCounts);
        System.out.println("Method 2 - Procedural loop but inner loop replaced with format specifiers");
        printInStarsWithFormat(starCounts);
        System.out.println("Method 3 - Functional way of thinking");
        printInStarsFunctional(starCounts);
    }
}