Parent Component: Chunk 4: Storage
Storing information systematically is Java's goal!
Jump to a section
local_diningModule "hamburger" guide
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
Create arrays of primitive and String types
Iterate through arrays with for() loopsfixed
Access member variables and methods on objects stored in arraysfixed
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.
Each book has a label on it, such as books. The array is called books and the  through  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.
Filling the array with our book titles:
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;
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:
This output is generated with the following code:
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.
Notice that when we run this simplified code, we acheive the same output as when we used the temporary storage bariable extractedArrayValue.
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
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.
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:
Steps for creating your own array:
- Open a MS Word Document. Save it in Documents with a sensible name like: arraymodel.docx
- 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.
- Choose about 6-8 items to paste into the Word Document.
- Decide on a name for the entire collections, like books or cards or dvds
- 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
- 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.
- 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!
- 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.)
- Share your array with a peer. What would be the next interesting thing to do with this array?
Exercise 2: Creating and Processing Integer Arrays
Exercise type: Modeling life in Java
Study this image below of beakers holding writing instruments.
Create a class called IntegerArray. Add a main() method to your class
In main() Create an array of integer values that represent an approximate count of the number of instruments in each beaker.
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:
- Make a paper diagram of your method. Include the input and output types, what it will be called, and draft what actions it will take inside the method body.
- We'll need a variable called something like runningTotal which we will add the number of instruments to each time we go through the loop, visiting one bin at a time
- The runningTotal should probably be the value that is returned to the calling method.
- Test your method by writing a call to that method from main, passing in the integer array we created of each writing instrument beaker.
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
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.
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:
- 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
- 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.
- 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.
- 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!
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:
- 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.
- 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.
- 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.
- Now that you have these systems working, build in processes to both the input amounts are checked to avoid an IndexOutOfBoundsException
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.
- Create a new package called objectifiedarrays and a new package with the same name. Create a class called ArrayOfObjects
- 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.
- 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.
- 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.
- 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!
- 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.
- The user should now be given the chance to inspect any item he/she/they created and stored in the array. Create this interface.
- 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.