Unit 2 · Java Fundamentals · 8 min
Arrays
An array stores many values of the same type under one name, reached by position (index) starting at 0.
Why this matters
When you need 50 student marks, you do not create 50 variables. Arrays plus loops solve that in a few lines.
Real-life analogy
An array is a row of lockers with numbers painted on them. The row has one name, and each locker has an index starting from 0.
Syntax
Syntax
int[] marks = new int[5];
int[] marks = {80, 75, 90};Example
Java
public class Marks {
public static void main(String[] args) {
int[] marks = {80, 75, 90, 65, 88};
int total = 0;
for (int i = 0; i < marks.length; i++) {
System.out.println("Subject " + (i + 1) + ": " + marks[i]);
total += marks[i];
}
System.out.println("Total = " + total);
System.out.println("Average = " + (total / (double) marks.length));
}
}Output
Subject 1: 80 Subject 2: 75 Subject 3: 90 Subject 4: 65 Subject 5: 88 Total = 398 Average = 79.6
Step by step
- 1`{80, 75, 90, 65, 88}` creates an array of 5 ints already filled.
- 2`marks.length` is 5 — note it is a field, not a method, so no brackets.
- 3Indexes run from 0 to length-1, so marks[0] is 80 and marks[4] is 88.
- 4`(double) marks.length` casts to double so the average keeps its decimals.
Key points
- Array indexes start at 0
- Array size is fixed once created
- array.length is a field; String uses length() as a method
- Going past the last index throws ArrayIndexOutOfBoundsException
Common mistakes
- Using marks[5] on an array of size 5
- Writing marks.length() for an array
- Expecting an array to grow automatically — use ArrayList for that
Try it yourself
- Find the largest number in an array.
- Read 5 numbers from the user into an array and print them in reverse.