Part 04 / Topic 2 of 10
Iterating arrays: index loop vs. for-each
Two ways to walk through an array. Use the index loop when you need the position (to print "item 1, item 2...", to compare neighbours, to write into a slot). Use for-each when you only need the values, one at a time, and don't care which slot they came from.
import java.util.Arrays;
class ArrayBasics {
public static void main(String[] args) {
int[] prices = {1200, 450, 1999, 80};
System.out.println("Number of items: " + prices.length);
for (int i = 0; i < prices.length; i++) {
System.out.println("Item " + i + ": ₹" + prices[i]);
}
int total = 0;
for (int price : prices) {
total += price;
}
System.out.println("Total: ₹" + total);
prices[1] = 500; // writing needs the index loop's prices[i]
System.out.println(Arrays.toString(prices));
int[] bill = new int[3];
System.out.println(Arrays.toString(bill));
String[] names = new String[2];
System.out.println(Arrays.toString(names));
}
}
Output (examples/01_array_basics.java):
Number of items: 4
Item 0: ₹1200
Item 1: ₹450
Item 2: ₹1999
Item 3: ₹80
Total: ₹3729
[1200, 500, 1999, 80]
[0, 0, 0]
[null, null]
System.out.println(prices) alone would print something unreadable like [I@1b6d3586 — an array has no built-in "print my contents" behaviour. Arrays.toString(...) (from java.util.Arrays) is the ready-made way to see a 1D array's contents.
⚠️ A fixed-size array never resizes.
prices[1] = 500changes slot 1. There is noprices.add(...); arrays have no such method. If you don't know the final count ahead of time, you wantArrayList(section 4), not an array.
Full program: examples/01_array_basics.java.
Done here? The practice set for Part 4 — including the solutions — is on the part page.