Java Arrays
An array stores many values of the same type in one variable.
Creating an Array
Put the values inside curly braces, and add [] after the type:
Example
String[] students = {"Ali", "Ayesha", "Bilal", "Sana"};
int[] marks = {78, 91, 64, 85};You can also create an empty array of a fixed size. Every item starts with a default value (0 for numbers, null for objects):
Example
int[] scores = new int[5]; // five zerosReading and Changing Items
Each item has an index. The first item is at index 0.
Example
public class Main {
public static void main(String[] args) {
String[] students = {"Ali", "Ayesha", "Bilal", "Sana"};
System.out.println(students[0]);
System.out.println(students[2]);
students[2] = "Hamza";
System.out.println(students[2]);
System.out.println("Total: " + students.length);
}
}Ali Bilal Hamza Total: 4
| Code | Meaning |
|---|---|
arr[0] | The first item |
arr[arr.length - 1] | The last item |
arr.length | How many items (no brackets, it is not a method) |
Using an index that does not exist, like students[4] in an array of 4 items, crashes the program with an ArrayIndexOutOfBoundsException.
Looping Through an Array
Use a for loop when you need the index, or a for-each loop when you only need the values:
Example
public class Main {
public static void main(String[] args) {
int[] marks = {78, 91, 64, 85};
int total = 0;
for (int i = 0; i < marks.length; i++) {
System.out.println("Student " + (i + 1) + ": " + marks[i]);
total += marks[i];
}
System.out.println("Average: " + (total / (double) marks.length));
}
}Student 1: 78 Student 2: 91 Student 3: 64 Student 4: 85 Average: 79.5
Finding the Highest Value
Example
int[] prices = {350, 1200, 799, 450};
int highest = prices[0];
for (int p : prices) {
if (p > highest) {
highest = p;
}
}
System.out.println("Highest: Rs " + highest);Highest: Rs 1200
Sorting and Printing with Arrays
The java.util.Arrays class has ready-made helpers:
Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {5, 2, 9, 1};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
}
}[1, 2, 5, 9]
Two-Dimensional Arrays
A 2D array is an array of arrays, like a table with rows and columns:
Example
int[][] seats = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(seats[1][2]); // row 1, column 26
Exercise
Exercise
An array has 6 items. What is the index of the last item?
