What Are Arrays?
Arrays are like containers that let you store multiple values in a single variable. This is handy because it saves you from declaring a bunch of separate variables for related values.
Declaring an Array
To declare an array, you specify the variable type followed by square brackets. For instance:
String[] motorcycles;
This line of code declares a variable that holds an array of strings. To populate this array with values, you can use curly braces and list the values separated by commas:
String[] motorcycles = {"Harley", "Ducati", "Yamaha", "Kawasaki"};
If you want to create an array of integers, it would look like this:
int[] engineCapacities = {600, 750, 1000, 1200};
Accessing Array Elements
You can access individual elements in an array by referring to their index number. For example, to access the first element in the motorcycles
array:
String[] motorcycles = {"Harley", "Ducati", "Yamaha", "Kawasaki"}; System.out.println(motorcycles[0]); // Outputs Harley
Note: Array indexes start at 0, so the first element is at index 0, the second element is at index 1, and so on.
Modifying an Array Element
To change the value of a specific element in an array, you refer to its index number. For example:
String[] motorcycles = {"Harley", "Ducati", "Yamaha", "Kawasaki"}; motorcycles[0] = "Suzuki"; System.out.println(motorcycles[0]); // Now outputs Suzuki instead of Harley
Determining the Length of an Array
To find out how many elements an array contains, you can use the length
property:
String[] motorcycles = {"Harley", "Ducati", "Yamaha", "Kawasaki"}; System.out.println(motorcycles.length); // Outputs 4