Array Basics & Iteration
Understand array basics: fixed-size, zero-based indexing, create/initialize, and iterate safely.
What is an array
Array is a fixed-size sequence of elements of the same type, stored under one name and indexed from 0.
- Use when you know the element count
- Access by index: first is 0
- Type-safe: all items have the same type
Declare & Create
Declare and create arrays:
public class Main {
public static void main(String[] args) {
// Way 1: Declare an array with fixed size
int[] a = new int[3];
// All elements are 0 by default: [0, 0, 0]
// Way 2: Declare and initialize in one line
int[] b = {10, 20, 30};
// This array already has values: [10, 20, 30]
// Print both arrays
System.out.print("Array a: ");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println(); // new line
System.out.print("Array b: ");
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
}
All lessons in this course
- Array Basics & Iteration
- Searching, Min/Max & Reverse
- Insert, Delete by Index & Shift