Java Arrays
An array holds several values of the same type. Its size is fixed when you create it, and positions (indexes) start at 0.
ExampleJava
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford"};
System.out.println(cars[0]); // Volvo
cars[1] = "Opel";
System.out.println(cars.length); // 3
System.out.println(Arrays.toString(cars));
int[] nums = new int[3]; // {0, 0, 0}
nums[2] = 7;
System.out.println(Arrays.toString(nums));
int[] scores = {5, 2, 9, 1};
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));
int[][] grid = {{1, 2}, {3, 4}}; // 2D array
System.out.println(grid[1][0]); // 3
}
}Output
Volvo 3 [Volvo, Opel, Ford] [0, 0, 7] [1, 2, 5, 9] 3
Quick check
What is the index of the first element of an array?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.