Java · Lesson 4 of 9
Loops & arrays
for, enhanced for, while, and working with arrays.
An array holds a fixed number of values of one type: int[] marks = {72, 88, 65};. Index from 0; marks.length gives the size. Reading past the end throws ArrayIndexOutOfBoundsException.
for (int i = 0; i < n; i++)— counted loop.for (int m : marks)— enhanced for: every element, read-only access.while (cond)anddo { } while (cond)(runs at least once).breakandcontinuework as in other languages.
java.util.Arrays has helpers: Arrays.sort(arr), Arrays.toString(arr).
Example program
Run with JDK 17+: java Main.javaimport java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] marks = {72, 88, 65, 91, 58};
int total = 0;
for (int m : marks) {
total += m;
}
System.out.println("Average: " + (double) total / marks.length);
int highest = marks[0];
for (int i = 1; i < marks.length; i++) {
if (marks[i] > highest) highest = marks[i];
}
System.out.println("Highest: " + highest);
Arrays.sort(marks);
System.out.println(Arrays.toString(marks));
}
}
Output
Average: 74.8
Highest: 91
[58, 65, 72, 88, 91]
Save the code as Main.java and run java Main.java (JDK 11+ runs single files directly). Names and figures are fictional.
Key points
- Arrays have fixed length.
- Enhanced for is simplest for reading every item.
- Arrays.sort / Arrays.toString save time.
Quick check
What is the last valid index of an array of length 5?
Indexes run from 0 to length − 1, so 0–4.
Practice task
Count how many marks in the array are 70 or above and print the count.
Interview corner
Array vs ArrayList?
An array has a fixed size and can hold primitives. ArrayList grows automatically, holds objects only and offers methods like add and remove.
How do you reverse an array in place?
Swap elements from both ends moving inward: for i from 0 to n/2, swap arr[i] and arr[n-1-i].
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.