Why arrays?
Imagine storing the marks of 50 students. Making 50 variables (mark1, mark2...) would be painful. An array holds many values of the same type under one name.
Think of it like this: An array is like a row of numbered lockers. Every locker holds one thing, and you find a locker by its number.
Creating an array
public class Main {
public static void main(String[] args) {
int[] marks = {78, 92, 65, 88};
String[] names = {"Asha", "Ravi", "Meera"};
System.out.println(marks[0]);
System.out.println(names[2]);
System.out.println(marks.length);
}
}Output
78 Meera 4
int[]means “an array of ints”.- Positions (indexes) start at 0, just like in strings.
.length(no brackets!) tells you how many items there are.
Changing an element
public class Main {
public static void main(String[] args) {
int[] marks = {78, 92, 65, 88};
marks[2] = 70;
System.out.println(marks[2]);
}
}Output
70
An empty array of a fixed size
If you don't know the values yet, say how many lockers you want. Java fills them with a default: 0 for numbers, false for booleans, null for Strings:
public class Main {
public static void main(String[] args) {
int[] scores = new int[3];
scores[0] = 50;
System.out.println(scores[0]);
System.out.println(scores[1]);
}
}Output
50 0
Remember: An array's size is fixed when you create it. It can't grow later (for that, use
ArrayList– coming in a later module).
Going past the end
public class Main {
public static void main(String[] args) {
int[] marks = {78, 92, 65, 88};
System.out.println(marks[4]);
}
}Output (Java stops with an error)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
Common mistake: An array of length 4 has indexes 0, 1, 2 and 3. The last index is always
length - 1.