Create fixed-size arrays, read and change elements by index, loop over them, and use Arrays helpers for sorting and printing.
Why: an array is a fixed-size, ordered list of values that all share one type. You either give the values up front in braces, or create an empty array of a set size that fills with defaults (0 for numbers, null for objects).
int[] scores = { 90, 85, 100 }; // size fixed at 3
String[] names = new String[2]; // 2 empty slots (both null for now)
names[0] = "Ada";
names[1] = "Alan";
System.out.println(scores.length); // 3 — note: a field, not a methodWhy: each slot has a position (index) starting at 0. You read and overwrite slots with square brackets. Going past the end throws an ArrayIndexOutOfBoundsException, so the last valid index is always length - 1.
int[] scores = { 90, 85, 100 };
System.out.println(scores[0]); // 90 (first)
System.out.println(scores[scores.length - 1]); // 100 (last)
scores[1] = 88; // overwrite the middle one
System.out.println(scores[1]); // 88Why: the enhanced for loop ("for-each") is the cleanest way to visit every element when you do not need the index. Use a classic indexed for loop when you need the position or want to change elements.
int[] scores = { 90, 85, 100 };
// for-each: read each value
for (int score : scores) {
System.out.println(score);
}
// indexed: when you need the position
for (int i = 0; i < scores.length; i++) {
System.out.println("Position " + i + " = " + scores[i]);
}Why: arrays themselves have almost no methods, so the Arrays utility class fills the gap — sorting, searching, and printing. Printing an array directly shows gibberish, so use Arrays.toString().
import java.util.Arrays;
int[] scores = { 90, 85, 100 };
Arrays.sort(scores); // sorts in place: {85, 90, 100}
System.out.println(Arrays.toString(scores)); // [85, 90, 100]
System.out.println(scores); // gibberish like [I@1b6d3586 — avoidWhy: an array can hold other arrays, giving you a grid (rows and columns) — useful for tables, game boards, and matrices. Use two indexes: the first picks the row, the second the column.
int[][] grid = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
System.out.println(grid[0][2]); // 3 (row 0, column 2)
System.out.println(grid[1][0]); // 4 (row 1, column 0)
System.out.println(grid.length); // 2 (number of rows)