★ array creation and access
- most programming languages have a simple data structure for a collection of related data.
- block-based programming: called a list
- others (like java): array
- array — block of memory that stores a collection of data items (elements) of the same type under one name.
- useful when you have many elements of data of the same type you want to keep track of, but you don’t need to name each one
- you use the array name and a number (index) for the position of an item in the array
- you can make arrays of ints, doubles, Strings, and even classes that you have written
- (it’s like a row of small lockers, but you can only store value each locker)
- most languages start from the number 0 when counting elements
- when we declare a variable, we specify its types and then the variable name. if we want to make a variable into an array, we put square brackets after the data type
- for example,
int[] scores means we have an array called scores that contains int values
- the declarations do NOT create the array. arrays are objects so any variable that declares an array holds a reference to an object
- if the array hasn’t been created yet and you try to print the value of the variable, it will print null
- two ways to create an array:
- keyword new to get new memory
- use an initializer list to set up the values in the array
- use the new keyword with the type and size of the array (the number of elements it can hold) - which will create the array in memory
- declaration & creation in one step
//declare an array variable
int[] highScores;
// create the array
highScores = new int[5];
// declare and create array in 1 step!
String[] names = new String[5];
which of the following creates an array of 10 doubles called prices?
A) int[] prices = new int[10];
B) double[] prices = new double[10];
C) double[] prices;
D) double[10] prices = new double[];
<aside>
🧾 note: array elements are initialized to default values
-
0 for elements of type int
-
0.0 for elements of type double
-
false for elements of type boolean
-
null for elements of type String
</aside>
-
when using an initializer list, you set the values in the array to a list of values in curly braces when you create it
- you don’t specify the size, it will determined from the number of values that you specify