CS 112
Spring 2018

Old version

This is the CS 112 site as it appeared on May 11, 2018.

Lab 2: Arrays and blueprint classes

FLR 267

If your lab meets in FLR 267, you should begin by following the instructions found here.

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 lab2 for your work on this lab, and put all of the files for this lab in that folder. If you are working on a lab machine, you will need to create the folder on the Z: drive, so that it won’t be lost when you log out.

Task 0: Piazza tips and reminders

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 DrJava, and implement the following array-processing methods in a class named Lab2Task2.

Note: You do not need a main() method. Rather, once you are ready to test one of the methods, you can simply compile the class and enter test calls from the Interactions Pane – prepending the class name – as shown in the examples below.

  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};
    > Lab2Task2.square(a1)
    > a1
    { 1, 4, 9, 16 }
    

    (Note that if you evaluate an array variable in the Interactions Pane, DrJava is nice enough to show you the contents of the array, even though printing that same variable would show something based on the array’s memory address.)

  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};
    > Lab2Task2.shiftLeft(a2)
    1
    > a2
    { 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.

Task 3: Understand and modify a blueprint class

Consider the following class, which contains the beginnings of a blueprint class for Point objects: Point.java.

Each Point object represents a single point with integer coordinates (x, y).

  1. Read through the file to understand what is already completed.

  2. Compile the code in DrJava, and then go to the Interactions Pane. Fill in the blanks below to create a Point object with an x-coordinate of -2 and a y-coordinate of 5, and then enter the command at the prompt:

    > ______ p1 = ________________
    
  3. The current version of the class does not employ appropriate encapsulation. To see that, try entering the following expressions after you create p1:

    > p1.x
    -2
    > p1.y
    5
    > p1.x = 0;
    

    In a properly encapsulated class, code entered from the Interactions Pane should not be able to directly access the fields. Make whatever changes are needed to prevent this, and then recompile the class.

    If you’ve been successful, you should now see something like this:

    > Point p1 = new Point(-2, 5);
    > p1.x
    Static Error: No field in Point has name 'x'
    > p1.y
    Static Error: No field in Point has name 'y'
    

    Although the error messages are a bit misleading, the fact that we are no longer allowed to directly access the fields from the Interactions Pane means that we have correctly protected them.

  4. To provide indirect access, add an accessor method and a mutator method for each field.

    Note that each coordinate can take on any integer value, which means that the mutators don’t need to perform any error-checking, and that we also don’t need to add any error-checking to the constructor. However, keep in mind that ordinarily you do need error-checking in your mutators and constructors.

  5. What value is printed when you do the following?

    > Point p1 = new Point(-2, 5);
    > System.out.println(p1);
    

    To see something more descriptive, uncomment the toString() method in the class, and then save and recompile it, and enter the lines above once again.

    Note that we don’t need to actually call the toString() method. Rather, it is called on our behalf whenever we print an object of the class.

  6. Add an accessor method called quadrant that returns the number of the quadrant (if any) in which the called Point object (this) falls. The method should return:

    • 1 if both coordinates are positive
    • 2 if the x coordinate is negative and the y coordinate is positive
    • 3 if both coordinates are negative
    • 4 if the x coordinate is positive and the y coordinate is negative
    • 0 if the point lies on the x-axis or y-axis

    For example:

    > Point p1 = new Point(3, 4);
    > p1.quadrant()
    1
    > Point p3 = new Point(-3, -4);
    > p3.quadrant()
    3
    > Point p5 = new Point(0, -4);
    > p5.quadrant()
    0
    
  7. Although most of the methods in a blueprint class are non-static (meaning that we can think of them as being inside each object of the class), they can also include static methods (which belong to the class as a whole).

    A non-static method is preferred if the method needs to access to the fields of a particular called object. However, if a method does not need a called object – i.e., if it makes more sense to pass in all of the information that it needs as parameters – then we typically make it static.

    Write a static method closestToOrigin() that takes two Point objects and returns the Point that is closest to the origin.

    Hint: Make use of the distanceFromOrigin() method that every Point has!

    Because the method is static, we must prepend the class name to call it from outside the class:

    > Point p1 = new Point(3, 4);
    > Point p2 = new Point(2, -1);
    > Point.closestToOrigin(p1, p2)
    (2, -1)
    

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

You should show the paper with your work on Task 1 to the teaching assistant.

You should use Apollo to submit the following files:

Don’t worry if you didn’t finish all of the tasks. You should just submit whatever work you were able to complete during lab.

Warnings

  • Make sure to use these exact file names, or Apollo will not accept your files. If Apollo reports that a file does not have the correct name, you should rename the file using the name listed in the assignment or on the Apollo upload page.

  • Make sure that you do not try to submit a .class file or a file with a ~ character at the end of its name.

  • Before submitting your files, make sure that your BU username is visible at the top of the Apollo page. If you don’t see your username, click the Log out button and login again.

  • If you make any last-minute changes to one of your Java files (e.g., adding additional comments), you should compile and run the file in DrJava after you make the changes to ensure that it still runs correctly. Even seemingly minor changes can cause your code to become unrunnable.

  • If you encounter problems with Apollo, close your browser and try again. If possible, you may also want to wait an hour or two before retrying. If you are unable to submit and it is close to the deadline, email your homework before the deadline to cs112-staff@cs.bu.edu

Here are the steps:

  1. Login to Apollo, using the link in the left-hand navigation bar. You will need to use your Kerberos user name and password.
  2. Check to see that your BU username is at the top of the Apollo page. If it isn’t, click the Log out button and login again.
  3. Find the appropriate lab section on the main page and click Upload files.
  4. For each file that you want to submit, find the matching upload section for the file. Make sure that you use the right section for each file. You may upload any number of files at a time.
  5. Click the Upload button at the bottom of the page.
  6. Review the upload results. If Apollo reports any issues, return to the upload page by clicking the link at the top of the results page, and try the upload again, per Apollo’s advice.
  7. Once all of your files have been successfully uploaded, return to the upload page by clicking the link at the top of the results page. The upload page will show you when you uploaded each file, and it will give you a way to view or download the uploaded file. Click on the link for each file so that you can ensure that you submitted the correct file.