Loading subject…
Static arrays are also known as fixed-size arrays because of their property.
There are different methods for starting to work with static arrays in Java:
Declaration: Specify the data type and name of the array.
Initialisation: Define the size and allocate memory.
Combined declaration and initialisation: Often used together to save space.
Initialisation with values:
When initialising an array with specific values, the size is automatically determined by the number of elements provided.
Accessing elements: Use the index to retrieve values.
Modifying elements: Assign new values using the index.
Displaying array elements: Iterate indices from 0 to length -1 and output the element.
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){ 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); } }}
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); }}
int[] numbers;numbers = new int[10]; // of length 10int[] numbers = new int[10];int[] numbers = {1, 2, 3, 4, 5, 6};System.out.println(numbers[0]); // output 0th element of the arraynumbers[3] = 10;