Static Arrays
- Static arrays are a fundamental data structure in programming, designed to store a fixed number of elements of the same data type.
- Unlike dynamic arrays, which can resize during runtime, static arrays have a predetermined size set during their initialisation.
Static arrays are also known as fixed-size arrays because of their property.
- Think of a static array as a row of lockers, each with a fixed position.
- You can store items in each locker, but you can't add more lockers or remove existing ones.
Declaring and Initialising Static Arrays (in Java)
There are different methods for starting to work with static arrays in Java:
Declaration: Specify the data type and name of the array.
int[] numbers;Initialisation: Define the size and allocate memory.
numbers = new int[10]; // of length 10Combined declaration and initialisation: Often used together to save space.
int[] numbers = new int[10];Initialisation with values:
int[] numbers = {1, 2, 3, 4, 5, 6};When initialising an array with specific values, the size is automatically determined by the number of elements provided.
Accessing and Modifying Array Elements
Accessing elements: Use the index to retrieve values.
System.out.println(numbers[0]); // output 0th element of the arrayModifying elements: Assign new values using the index.
numbers[3] = 10;- Array indices start at 0.
- Accessing an index outside the valid range (0 to length - 1) will result in an ArrayIndexOutOfBoundsException.
Common Operations on Static Arrays
- Avoid hardcoding array sizes or indices.
- Instead, use the array's length property to ensure your code adapts to changes in array size.
Displaying array elements: Iterate indices from 0 to length -1 and output the element.
public class Main{
public static void main(String[] args){
String[] names = {"Alice", "Bob", "Christopher", "Darcy"};
// for loop
for (int i = 0; i < names.length; i++){
System.out.println(names[i]);
}
System.out.println("-----");
// or shorter using for-each loop
for (String person: names){
System.out.println(person);
}
}
}
Summing array elements: Iterate indices from 0 to length -1 and add the element to the sum variable.
public class Main{
public static void main(String[] args){
int[] numbers = {10, 5, 3, 8, 2, 18, 2};
int sum = 0; // initialise sum variable
for (int i = 0; i < numbers.length; i++){
sum += numbers[i]; // add element to the sum
}
System.out.println("The sum is: " + sum);
}
}
- What is the main disadvantage of static arrays?
- Try to write a program that:
- Finds a minimum element in a given array
- Finds a specified element in a given array and returns its index (linear search)