flasks
We can model real stuff in the real world with arrays in Java!

Module: Arrays

Parent Component: Chunk 4: Storage

Storing information systematically is Java's goal!

Jump to a section

local_diningModule "hamburger" guide
check_boxLearning Objectives
extensionCore Concepts: Modeling Books in an Array
bookResources and reference documents
motorcycleExercise 1: Creating your own collection!
motorcycleExercise 2: Arrays of integer values
motorcycleExercise 3: Reusing our methods with an array of flasks
motorcycleExercise 4: Adding user interaction to our arrays
flight_takeoffExtension Exercises: Arrays and an object model


Learning Objectives

check_box

Create arrays of primitive and String types

check_box

Iterate through arrays with for() loopsfixed

check_box

Access member variables and methods on objects stored in arraysfixed

arrow_upward


book

External Resources

Oracle Tutorial on Arrays

Oracle Tutorial on For() loops

arrow_upward


extension

Module Core Concepts

Part 1: Creating and filling arrays with values

Arrays store data of all the SAME TYPE in bins numbered starting at zero. If we want to store chunks of text in each array, then we'd create an array of String objects.

Let's build an array to represent this stack of programming books. We'll store the titles of each book in an array that has one bin for each book: a total of 5 bins.

We can model collections of related objects in Java arrays. An array is declared with a certain type, meaning it can only hold the type it was delcared to hold. In this case, the book titles are Strings, so each array bin holds a single String object.

Java code for the creation of a String array with 5 bins:
java code for creating arrays
We use the keywork mew when creating an array just like we do other objects, such as new Donut(); back in DonutLand.

Each book has a label on it, such as books[0]. The array is called books and the [0] through [4] represent the index of the bin. Study this image and review the code that follows for loading up String values into each of the 5 array compartments.

O'Reilley Programming Books
books array
In the early days of publishing, content was physically printed in bound volumes. The following image of programming books was obtained after much negotation from the national historic book archive.

Filling the array with our book titles:

Fililng Array
Now that we access each bin of the array through its indexes, which range from 0 to 4. NOTICE: when we create an array, we tell the compiler how many bins to have using "human" counting numbers--starting at 1. But the INDEXES start at zero! This is something we have to memorize and check each time we work with arrays.

Part 2: Accessing contents of an array and sending values to the console:

Now that we have an array storing titles of all the books, we want to use that data somehow, such as for printing out an inventory of books in our collection.

Arrays bins are accessed the same way they are accessed for storing values: provide the name of the array followed by the index of the desired bin in [square brackets]. So we can retrieve the String that has the title of the book in index 2 with the following line of code:

String retrievedBook = books[2];

We can use this pattern to visit and print out data from each of our array bins in books. We want to generate some nicely formatted output showing our inventory of books that looks something like this:

Sample output of a total printing of the books array
Printing an array
Each bin of the array is visited and printed out on a single line.

This output is generated with the following code:

Visiting each array bin, storing the String, and printing it
printing with basic methods
This simple but inefficent method visits each bin of the array, retrieves the value, stores it in a temorary hold variable called extractedArrayValue, and then sends that value to the println() along with a String "lead in" so we know what the output means.

Part 3: A more efficient printing mechanism:

The code above uses the variable extractedArrayValue to hold the String that is stored in each array bin for just a single line of code: we turn right around and print out the value of extractedArrayValue. We can remove the "holding" variable and simple visit each bin of the array directly inside our call to println(). This is possible because books stores String objects, which println() accepts as an argument to its method.

A more compact method for printing an array of Strings to the console:
printing with while
Accessing an array of Strings directly inside our call to println(), saving us from using a pointer variable.

Notice that when we run this simplified code, we acheive the same output as when we used the temporary storage bariable extractedArrayValue.

Sample output of a total printing of the books array
printing with for
Each bin of the array is visited and printed out on a single line.

Runtime Exceptions: IndexOutOfBoundsException

The Java Virtual Machine relies on us the programmer not to try to write or read data from an array bin with an index greater than the maximum bin index created when the Array is generated with the new keyword. In other words, if we have an array of 5 items and

Sample output of an attempt to access an array index that's higher than the largest index of the books array (which is 4):
Java exception from processing arrays
Exception messages are very helpful! Notice that the name of the exception gives us a clue about what error exists in the code.

Challenge: Edit your code such that you generate a runtime exception like the one above. You'll need to tinker with the array index values that you try to retrieve or write to.

arrow_upward


motorcycle

Exercise 1:Create your own collection and represent it in an array

Exercise type: Apply Java to your life!

Complete the following steps to create and share an array of items that are of interest to you. Here's a sample of a student's work:

A fashion-conscious student modeled his collection of hoodies manufactured by the UnderArmour corporation:
UnderArmour hoodies
The code that represents this array is shown along with a for() loop for printing its contents.

Steps for creating your own array:

  1. Open a MS Word Document. Save it in Documents with a sensible name like: arraymodel.docx
  2. Decide on a category of object or item you either DO or WOULD LIKE to collect. Use an internet image search tool to copy and paste images into the Word document.
  3. Choose about 6-8 items to paste into the Word Document.
  4. Decide on a name for the entire collections, like books or cards or dvds
  5. Like the example above, use text boxes or tables to label each item with the name of the array and its index --REMEMBER indesxes start at zero
  6. Now model the array you built in images in Java-- meaning create a new array object of the appropriate type. With that empty object, you can then fill in values for each of your items in the collection.
  7. Now that you have the array filled, practice accessing the array by writing a method that you pass the array to which loops through it with a for() loop, displaying its contents. Review the Oracle documentation on for() loops as you do this!
  8. Take screen clips (using the Windows snipping tool) of your array images, your array code, and output. Paste them into our shared google drive of student arrays NOTE: In order to upload to our shared google drive, you must be signed into any google account (gmail, google drive, etc.)
  9. Share your array with a peer. What would be the next interesting thing to do with this array?

arrow_upward


motorcycle

Exercise 2: Creating and Processing Integer Arrays

Exercise type: Modeling life in Java

Study this image below of beakers holding writing instruments.

Writing Arrays

Exercise Steps

Step 1:

Create a class called IntegerArray. Add a main() method to your class

Step 2:

In main() Create an array of integer values that represent an approximate count of the number of instruments in each beaker.

Step 3:

Write a method to print out the contents of the integer array. The method should be called printNumericArrayManually. Look back at our previous examples. You may decide to print the array manually or to use a looping mechanism, such as a while() or for() loop

Using while() loops for printing

We should see that this process is repetitive: we have lots of repeated code, such as println() calls and hard-coded values. Looping mechanisms are much more flexible, since they can check the array size automatically and code is not repeated, it is just looped.

Review the Oracle documentation on while() loops as you do this!

Using for() loops for printing

for() loops are the ideal candidate for this repetitive printing task since the for() loops can be thought of us packaged while() loops with some extra built-in functions to help us loop through arrays and other objects that are indexed with numbers.

Review the Oracle documentation on for() loops as you do this!

Step 4: Compute sums

Create a method that takes in an integer array and computes the sum of all values entered into the array

Some building guidelines and ideas:

Step 5: Calling our summing method

Remember that the only method that the Java Virtual machine will call for us is the main() method, where the control panel for the system exists. So we now need to call up the method that we just created, passing to that method the reference to our array of integers. Write the call to your array that computers averages:

Step 6: Calculating average pen counts

Create a method that calculates the average value across the array. Remember we calculate averages by dividing the sum of the elements we want to average by the number of elements we're averaging (sum divided by parts).

Your method should take in an array of integers and return a double value representing the average contents of the beakers. Don't forget to call the method that you just wrote from main().

Review the entire source code for our IntegerArray class on GitHub:

Review the GitHub code for this class

arrow_upward


motorcycle

Exercise 3: Using our integer array to process arrays of flasks filled with mysterious liquids

Now that we have created methods for printing arrays of integers and methods for calculating sums and averages of their values, we can reuse those methods to process arrays that represent other integer values.

Creating an array of flasks

The high level view of this activity is that we want to create a new method inside class IntegerArrays that creates a new array that represents the fluid level of each of these erlenmeyer flasks.

We can summarize the steps here:

  1. Create a new method in IntegerArrays to manage this process. This method should be called createAndAnalyzeFlasksArray() and does not take any parameters or return any values
  2. Once you have that method created with the proper signature, create an array of ints to represent each of the flasks. Load up that array with approximations of the fluid level in each flask.
  3. We already have methods written to print out the contents of this array. Call one of your printing methods and verify that the results are printed correctly.
  4. We now want to use our summing and averaging methods to gather some basic statistics about the flasks. Each method independently, capture the return value, and print that return value to the console with proper labeling.

This exercise is a seriously solid exercise. Check the code for this entire method with the button below!

arrow_upward


motorcycle

Exercise 4: Adding User Interaction to our array classes

Exercise type: Embellishing our code

Obviously, creating code that stores data in arrays and then spits that back out is only the beginning of the process of using data structures in Java. One step to a more complicated program is to allow the user to interact with our data structures by either choosing the value to add to the array or requesting a certain array bin's value. Work through the following steps to create user input around one of our array models:

  1. Pick one of the arrays we've built so far (your personal array, the books, the pens, or the flasks) and create a method in that class called facilitateUserInteraction() that will take in an array as a parameter and return nothing.
  2. In this method, create a Scanner object that can read data from the console input. Our first project will be to just allow the user to view any bin of the array he/she/they would like. Create a prompt for the user to enter the number of the array bin that they would like to see revealed. NOTE that this process should use the human readable convention that the first array bin is numbered as 1 and not 0. You'll need to be careful to convert the user input to the zero-indexed array access numbers so that there are no errors in your code.
  3. Phase two of this process is for the user to be able to fill in an array with values that he/she/they chooses and can then access once the array is full. Continue with the array that you used in the previous number such that the user is now prompted to decide how many values to include in the array, enter those values, and then get prompted for which array bin to check.
  4. Now that you have these systems working, build in processes to both the input amounts are checked to avoid an IndexOutOfBoundsException

arrow_upward


flight_takeoff

Extension activity: Create an object model and use an array to store those objects

Exercise type: Object Modeling

We have been filling our arrays with simple values: Strings and integers. The real power of java comes when we are creating our own objects using classes as blueprints and then manipulating those objects by storing them in arrays, removing them, and tinkering with their contents. This exercise will walk you through the process of creating a small class to model one of our collected objects, storing those in an array, and then manipulating that array with methods.

  1. Create a new package called objectifiedarrays and a new package with the same name. Create a class called ArrayOfObjects
  2. Choose one of the array systems we have created in this module that you'll model as an object. This example will use the Erlenmeyer flasks as an example. Create a small model of how you would create a blueprint for this object in Java. Ask yourself what the 2 or 3 member variables might be. For an Erlenmeyer flask, options would be: total capacity, current volume, size, material, manufacturer, and others.
  3. Once you have brainstormed this list of member variables, create a new class with the name of your object and code it up. Choose appropriate variable types for each member variable. Make each one private and create getter and setter methods to access those private variables.
  4. Back in the class called ArrayOfObjects, create a main() class and start to asseble an array of objects that you create for each separate bin. So if I'm creating Flask objects, I'm going to create a new Flask for each bin of the array. One keyword new for each Flask I want to create. Store each new Object in your array.
  5. Once you have the array filled, create a for() loop that can access each of the array bins and print out some basic information about each object. So if the Flask objects have a current volume, the accessing method will extract the reference for that object and the call a method to access its current liquid volume, and send that data to the console. You can call retrieve several variables from each object when you do the printing. This is a somewhat new process, so take your time. Remember, you access data on an object with the small but mighty dot (.) operator!
  6. Now that you can print data about each of the objects in your array, create a system such that the user can participate in the creation process of each object such as a Flask. They are prompted to enter values for each of the member variables on each object, and then the object is filed away into the array.
  7. The user should now be given the chance to inspect any item he/she/they created and stored in the array. Create this interface.
  8. Now create methods that traverse (look at each array bin) and determine basic stats, such as flagging any Flask that is too low on magic liquid, or is near capacity. Adapt the average and sum methods from above to work with Flask objects instead of primitive values.

arrow_upward