110 likes | 243 Views
Arrays. Chapter 7 day 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.
E N D
Arrays Chapter 7 day 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 with no () • To access a specific value put the index in [ ] count[2] += 4;
Using a for loop to initialize arrays int [] count = new int[13]; for(inti=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