High School Computer Science Notes
An array is a data structure used to store multiple values of the same type in a single variable.
Instead of creating many variables:
int score1 = 90;
int score2 = 85;
int score3 = 78;
int score4 = 92;
You can store them in one array:
int[] scores = {90, 85, 78, 92};
Now all values are stored together in one structure.
Arrays are useful when you need to:
Examples of array data:
Declaring an array tells Java:
dataType[] arrayName;
int[] numbers;
This tells Java:
numbers
To actually create the array in memory, we use the new keyword.
arrayName = new dataType[size];
int[] numbers;
numbers = new int[5];
This creates an array that can store 5 integers.
Most programmers combine the steps:
int[] numbers = new int[5];
This creates an array with 5 elements.
Each position in an array has an index. An index is the location of the value inside the array.
If an array size is 5, the last index is 4.
You assign values using the index number.
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
You can retrieve values using the index.
System.out.println(numbers[0]);
System.out.println(numbers[3]);
Output:
10
40
You can create and fill an array at the same time.
int[] numbers = {10, 20, 30, 40, 50};
Java automatically determines the array size.
This is equivalent to:
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
public class ArrayBasicsExample {
public static void main(String[] args) {
// Declare and initialize an array
int[] scores = {85, 90, 78, 92, 88};
// Access elements using indexes
System.out.println("First score: " + scores[0]);
System.out.println("Second score: " + scores[1]);
System.out.println("Third score: " + scores[2]);
// Modify a value
scores[2] = 80;
System.out.println("Updated third score: " + scores[2]);
}
}
Output:
First score: 85
Second score: 90
Third score: 78
Updated third score: 80
int[] numbers = new int[5];
numbers[5] = 100; // ERROR
Valid indexes are:
5 does not exist.
Error:
ArrayIndexOutOfBoundsException
Incorrect:
int[] numbers;
numbers[0] = 10;
Correct:
int[] numbers = new int[5];
numbers[0] = 10;
| Term | Definition |
|---|---|
| Array | A structure that stores multiple values of the same type |
| Index | The position of an element in the array |
| Declare | Define the array variable |
| Initialize | Create the array or assign values |
| Element | A value stored inside the array |
[ ] to access elementsint[] numbers = {10, 20, 30};
System.out.println(numbers[0]); // 10
System.out.println(numbers[1]); // 20
System.out.println(numbers[2]); // 30