CS 112
Fall 2020

Old version

This is the CS 112 site as it appeared on December 31, 2020.

Lab 4: Arrays, primitives and references

Using folders

We strongly encourage you to create a separate folder for each lab and each problem set, so that you can more easily keep track of your work. For example, you could create a folder called lab3 for your work on this lab, and put all of the files for this lab in that folder.

Piazza Pointers

Task 0: Review Strings and Static Methods from Lab 3, (optional)

Task 1: Arrays and references

Your work for this task should go on the piece of paper that we give you. Please show your paper to a staff member before you leave the lab.

  1. Let’s draw what things look like in memory for the each of the following code snippets:

    // snippet A
    int[] a1 = {1, 2, 3, 4};
    int[] a2 = a1;
    
    // snippet B
    int[] b1 = {1, 2, 3, 4};
    int[] b2 = {1, 2, 3, 4};
    
  2. Given the two snippets above, what is the value of the following expression?

    a1 == a2
    
  3. Given the two snippets above, what is the value of the following expression?

    b1 == b2
    
  4. Consider the following static method:

    public static void mystery(int[] vals) {
        for (int i = 0; i < vals.length; i++) {
            vals[i] *= -1;
        }
    
        int[] vals2 = new int[vals.length];
        for (int i = 0; i < vals.length; i++) {
            vals2[i] = vals[i];
        }
        vals = vals2;
    
        for (int i = 0; i < vals.length; i++) {
            vals[i] += 2;
        }
    }
    

    What does the array a1 look like after the execution of the following code snippet, which you many assume is part of the main method of a valid Java class?

    int[] a1 = {1, 2, 3, 4};
    mystery(a1);
    

    Draw pictures to show what things look like in memory. You may find it helpful to use the following template, which shows separate method frames for main() and mystery():

    +--------------+
    | mystery      |
    | -------      |
    |       +----+ |
    | vals2 |    | |
    |       +----+ |
    |       +----+ |
    |  vals |    | |
    |       +----+ |
    +--------------+
    | main         |
    | ----         |
    |       +----+ |
    |    a1 |    | |
    |       +----+ |
    +--------------+
    

Task 2: Array methods

Open your IDE, and implement the following array-processing methods in a class named ArrayPractice.

  1. Write a main method that you will use to test all your methods. But first, try this:

    Example:

    int[] a = {2, 4, 6, 8};
    System.out.println( a );
    

    What do you expect to see? What if we changed the statement as follows:

    System.out.println( Arrays.toString(a) );
    

    Now, what do you expect to see?

  2. Write a method named equals that takes two arrays of integers, and determines if each of the two arrays are identical (i.e. same elements in the same sequence). The method should return true or false accordingly.

    For this (and each of the following methods), you will need to add calls to your main method to test them.

    Example:

    int[] a1 = {1, 2, 3, 4};
    int[] a2 = {1, 2, 3, 4};
    System.out.println( a1 == a2 );
    

    should output:

    false
    

    and,

    System.out.println( equals(a1, a2) );
    

    should output:

    true
    

    Congratulations! You just wrote your own equals method for Arrays! However the Arrays class contains many methods, one of which is the equals method. To use the built-in Arrays method, try this:

    Example:

    System.out.println( Arrays.equals(a1, a2) );
    

    should output:

    true
    

Arrays vs Strings

Unlike strings, arrays are not immutable, meaning you can change the elements of the array. Therefore, creating two arrays with an initial assignment of the same literal values, creates two separate and independent arrays on the heap. Whereas:

String s1 = "Hello World";
String s2 = "Hello World";

The variables s1 and s21 reference the same literal string “Hello World” in Java’s String Constant Pool.

  1. Write a static method named square that takes an array of integers and squares each element of the array.

    This method does not need to return anything. (If you’re not sure why, please ask!)

    Example:

    int[] a1 = {1, 2, 3, 4};
    square(a1)
    System.out.println( Arrays.toString(a1) );
    

    should output:

    [1, 4, 9, 16]
    
  2. Write a static method named shiftLeft that takes an array of integers and shifts each element one position to the left. The last element of the array should end up being 0, and the original first element should be returned by the method.

    For example:

    int[] a2 = {1, 2, 3, 4, 5, 6};
    shiftLeft(a2)
    System.out.println( Arrays.toString(a2) );
    

    should output:

    [2, 3, 4, 5, 6, 0]
    

    Hint: To determine the necessary logic, you may find it helpful to begin by writing down examples of specific assignments statements that the method will need to perform as part of the shifting. Then look for the general pattern in these assignments, and use it to write the necessary loop.

    Other hints:

    • You will need to store the original first element in a variable before you do the shifting, so that you can return the first element at the end of the method.

    • Don’t forget to put a 0 in the last position of the array.

  3. Write a static method named replace that takes an array of integers and two integer variables, val1 and val2 and replaces all occurences of val1 with val2. The method should return how many values were replaced. If no value was replaced (i.e. there were no occurences of val1 in the array), the method should return a zero.

    For example:

    int[] a2 = {1, 2, 3, 2, 2, 6};
    int numReplaced;
    
    // first test
    numReplaced = replace(a2, 2, 9);
    System.out.println( Arrays.toString(a2) );
    System.out.println( "numReplaced = " + numReplaced);
    

    should output:

    [1, 9, 3, 9, 9, 6]
    numReplaced = 3
    

    and,

    // second test
    numReplaced = replace(a2, 2, 9);
    System.out.println( Arrays.toString(a2) );
    System.out.println( "numReplaced = " + numReplaced);
    

    should output:

    [1, 9, 3, 9, 9, 6]
    numReplaced = 0
    
  4. How could I produce the exact same output as above without needing to declare the variable numReplaced?

  5. What is the output of the following code segment?

    int[] a2 = {1, 2, 3, 2, 2, 6};
    
    replace(a2, 2, 9);
    System.out.println( replace(a2, 2, 9) );
    

Task 3: Challenge

  1. Write a static method named interChange that takes two arrays of integers, creates and returns a third array of integers which contains all the elements of the two arrays, but in interchangeable order.

    For example:

    int[] a1 = {1, 2, 3, 4, 5};
    int[] a2 = {6, 7, 8, 9, 10};
    int[] a3 = interChange(a1, a2);
    System.out.println( Arrays.toString(a3) );
    

    should output:

    [1, 6, 2, 7, 3, 8, 4, 9, 5, 10]
    

    Note:

    • If the arrays passed to the method are of two different sizes, only interchange elements until you run out of elements from the smallest array.
  2. Write a static method named isMirror that takes two arrays of integers and determines if the second array is an exact mirror image of the first array. The method should return true or false accordingly.

    For example:

    int[] a1 = {1, 2, 3, 4, 5};
    int[] a2 = {5, 4, 3, 2, 1};
    System.out.println( isMirror(a1, a2) );
    

    should output:

    true
    

    and

    int[] a3 = {1, 4, 5, 2, 1};
    System.out.println( isMirror(a1, a3) );
    

    should output:

    false
    
  3. Write a static method named isMirror that takes two arrays of Strings and determines if the second array is an exact mirror image of the first array. The method should return true or false accordingly.

    To ensure that you have written this method correctly, try the following two tests:

    String[] s1 = { "abc", "def", "ghi" };
    String[] s2 = { "ghi", "def", "abc" };
    String[] s3 = new String[3];
    s3[0] = new String( "ghi" );
    s3[1] = new String( "def" );
    s3[2] = new String( "abc" );
    
    System.out.println( isMirror(s1, s2) );
    System.out.println( isMirror(s1, s3) );
    

    Are the results the same? Why or Why not?

    Hint:

    • If the first call produces the expected results but the second test does not, consider how you are testing for equality on strings.

Extra Practice!

If you get through the exercises above, congratulations!

For extra practice, you can try some exercises from an excellent site called Practice-It.

Task 4: Submit your work

TBA