π4.3: Array Creation & Access
Table of Contents
π This page is a condensed version of CSAwesome Topic 4.3
β΄β΄β΄ NEW UNIT/SECTION! β΄β΄β΄
Create a blank Java program to take your class notes in for the next few lessons.
Click on the collapsed heading below for GitHub instructions ‡
π NOTES PROGRAM SETUP INSTRUCTIONS
- Go to the public template repository for our class: BWL-CS Java Template
- Click the button above the list of files then select
Create a new repository
- Specify the repository name:
CS2-Unit4PartA-Notes
- For the description, write:
1D Array data collections, using text files
- Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositories
section of GitHub! π - Now on your repository, click and select the
Codespaces
tab - Click
Create Codespace on main
and wait for the environment to load, then youβre ready to code! - π Take notes in this Codespace during class, writing code & comments along with the instructor.
π When class ends, donβt forget to SAVE YOUR WORK! Codespaces are TEMPORARY editing environments, so you need to COMMIT changes properly in order to update the main repository for your program.
There are multiple steps to saving in GitHub Codespaces:
- Navigate to the
Source Control
menu on the LEFT sidebar - Click the button on the LEFT menu
- Type a brief commit message at the top of the file that opens, for example:
updated Main.java
- Click the small
βοΈ
checkmark in the TOP RIGHT corner - Click the button on the LEFT menu
- Finally you can close your Codespace!
Array Creation and Access
To keep track of 10 exam scores, we could declare 10 separate variables:
int score1, score2, score3, β¦ , score10;
But what if we had 100 exam scores? That would be a lot of variables! Most programming languages have a simple data structure for a collection of related data that makes this easier. In many block-based programming languages like App Inventor and Scratch, this is called a list. In Java and many programming languages, this is called an array.
An array is a block of memory that stores a collection of data items (elements) of the same type under one name. Arrays are useful whenever you have many elements of data of the same type that you want to keep track of, but you donβt need to name each one. Instead, you use the array name and a number (called an index) for the position of an item in the array.
You can make arrays of int
, double
, String
, and even classes that you have written, like Student
.
Hereβs a video that introduces the concept of an array and gives an example.
An array is like a row of small lockers, except that you canβt cram lots of stuff into it β you can only store one value in each locker.
You can store a value in an array using an index (location in the array). An array index is like a locker number β it helps you find a particular place to store or retrieve something.
Index Basics
Arrays and lists in most programming languages start counting elements at 0. This means:
- The first element is at index
0
. - The second element is at index
1
. - The last element is at index
array.length - 1
.
Example:
int[] scores = {90, 85, 78, 92};
System.out.println(scores[0]); // prints 90
System.out.println(scores[3]); // prints 92
If you try to use an index less than 0
or greater than array.length - 1
, you will get an ArrayIndexOutOfBoundsException.
Activity: Image Array
Type this in your Codespace, press run, and experiment with the index
variable:
public class ImageEx {
public static void main(String[] args) {
String[] images = {
"cow.jpg", "kitten.jpg", "puppy.jpg", "pig.jpg", "reindeer.jpg"
};
ImageEx obj = new ImageEx();
int index = 0; // change this to show a different image
obj.printHTMLimage(images[index]);
}
public void printHTMLimage(String filename) {
String baseURL = "https://raw.githubusercontent.com/bhoffman0/CSAwesome/master/_sources/Unit6-Arrays/6-1-images/";
System.out.print("<img src=" + baseURL + filename + " width=500px />");
}
}
- Change
index
to show the puppy image, then the reindeer. - Try all images β what indices did you use?
- Replace
index
with a random number:(int)(Math.random() * images.length)
.
Coding Challenge: Countries Array
-
Create 4 parallel arrays for:
- Countries: China, Egypt, France, Germany, India, Japan, Kenya, Mexico, United Kingdom, United States
- Capitals
- Languages
- Image filenames
- Add more entries for countries you are interested in.
- Pick a random index using
Math.random()
and array.length
. - Print the country, its capital, its language, and its image using that index.
Arrays of Objects
You can create arrays of objects just like you create arrays of primitives. You must call the constructor for each object when initializing the array.
Example:
ClassName[] array = new ClassName[size];
array[index] = new ClassName();
array[index].method();
Activity: Turtle Array
import java.awt.*;
public class TurtleArray {
public static void main(String[] args) {
World world = new World(300, 300);
Turtle[] turtarray = new Turtle[2];
turtarray[0] = new Turtle(world);
turtarray[1] = new Turtle(world);
turtarray[0].forward();
turtarray[1].turnLeft();
turtarray[1].forward();
world.show(true);
}
}
Task:
- Change the array size to
3
. - Add another turtle at index 2.
- Make the new turtle turn right and move forward.
Community Challenge: Array of Your Class
- Copy your class from Lesson 3.5.
- Create an array of 3 objects of your class.
- Initialize each element using your class constructor.
- Call the
print
method for each object.
Summary
- (AP 4.3.A.1) Arrays store multiple values of the same type β primitives or object references.
- (AP 4.3.A.2) The size is fixed at creation and accessed via
.length
. - (AP 4.3.A.3) When created with
new
, elements are initialized to default values (0
,0.0
,false
, ornull
). - (AP 4.3.A.4) Initializer lists can create and populate arrays in one step.
- (AP 4.3.A.5) Square brackets
[]
are used to access or modify elements by index. - (AP 4.3.A.6) Valid indices are
0
tolength - 1
; accessing outside this range throws an error.
AP Practice
Example Problem:
public void mystery(int[] a, int i) {
a[i] = a[i-1] * 2;
}
If array
is {4, 10, 15}
, mystery(array, 2)
β {4, 10, 20}
.
Arrays Game
Try this array practice game. Click Arrays and guess which element will be printed. Turn on Labels if needed.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.