← Java tutorial

Java

Arrays

An array holds a fixed number of values of one type: int[] numbers = {1, 2, 3, 4, 5};.

Example: an enhanced for-loop over an array

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int total = 0;
        for (int n : numbers) {
            total += n;
        }
        System.out.println("Total: " + total);
    }
}
Total: 15

for (int n : numbers), read "for each int n in numbers", is Java's enhanced for-loop, and is generally preferred over a manual index-based loop whenever you don't actually need the index itself, just each value in turn. Access individual items by zero-based index (numbers[0]), and get the length with numbers.length, a field, not a method, so no parentheses.

Example
public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int total = 0;
        for (int n : numbers) {
            total += n;
        }
        System.out.println("Total: " + total);
    }
}
Output
Total: 15
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Closes Nov 30

Enroll in Backend Development

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account