ARRAYS
7.1
WHAT IS AN ARRAY?
• An array is a variable that collects a sequence of values
of the same type. It is essentially a variable with one
name, that sets aside multiple slots in memory to store
multiple values of the same type.
• Each slot has an index just like a string. The indexes start
at 0 and end at 1 less than the length.
FOR EXAMPLE
• An integer array called values would look like this:
DECLARING AN ARRAY
• An array can be of any type (primitive, or object)
• To declare an array, put [ ] after the type
• Ex:
int[ ] values;
//declares an integer array called values
Dice [ ] die;
//declares a Dice array called die
DECLARING AN ARRAY
• Before using an array, you must establish its size
• Ex:
int[] values;
values = new int[10];
Or
int[]values = new int[10]
IF YOU ARE PREPARED TO INITIALIZE RIGHT AWAY
• You can initialize and declare at the same time
int[] values = {2,12,33,15,16,47}
Note: Once size is set it cannot be changed!!
ARRAY VARIABLES STORE A REFERENCE!!!
• Much like object variables, Arrays store a reference or
memory address! Keep that in mind!!
int[] scores = {2,4,6,8,10};
int[]values = scores;
How many arrays are there?
LENGTH AND INDEX
• The length of an array is a constant, not a method. To
access the length you type
name.length
• To access a specific value put the index in [ ]
count[2] += 4;
with no ()
USING A FOR LOOP TO INITIALIZE ARRAYS
int [] count = new int[13];
for(int i=0;i<count.length;i++)
{
count[i]=0;
}
ARRAYS CAN BE PASSED AS PARAMETERS
• This is a valid method header
public void fillArray(int[] values)
HOMEWORK
• Create a program called DiceArray.
Add the Dice class to your
project. Write a short program which will create two dice objects,
roll the dice 1000 times, and will count and display how many
times each value 2-12 was rolled. Use an array
© Copyright 2026 Paperzz