By the end of this module, you will be able to:
.length property to work with array sizefor and enhanced for loopsArrayIndexOutOfBoundsExceptionArrays utility methods (Arrays.sort, Arrays.toString)An array is a fixed-size, ordered collection of elements of the same type. Think of it as a row of numbered boxes — each box holds one value, and each box has an index starting at 0.
Index: [0] [1] [2]
Value: "Alice" "Bob" "Charlie"
You already know arrays from JavaScript. The key difference in Java is that an array can only hold one type, and its size is fixed when created — it cannot grow or shrink.
Java gives you two ways to create an array.
Use this when you know how many elements you need but don't have the values yet.
int[] scores = new int[5];
// Creates: [0, 0, 0, 0, 0]
// All slots are filled with the default value for int (0)
Use this when you already know the values upfront.
String[] cities = {"Amsterdam", "Rotterdam", "Utrecht"};
// Creates: ["Amsterdam", "Rotterdam", "Utrecht"]
// Size is automatically determined by the number of values
Both syntaxes are valid — choose whichever fits your situation.
🔍 Coming from JS, Syntax 2 looks familiar. The difference is the type (
String[]) must be declared, and all elements must be that same type.
Use square bracket notation — same as JavaScript:
String[] cities = {"Amsterdam", "Rotterdam", "Utrecht"};
System.out.println(cities[0]); // Amsterdam
System.out.println(cities[1]); // Rotterdam
System.out.println(cities[2]); // Utrecht
⚠️ Arrays in Java are zero-indexed — the first element is always at index
0, and the last is at indexlength - 1.
.length PropertyEvery Java array has a .length property that returns the number of elements.
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers.length); // 5
<aside> 💭
In JavaScript, arrays have a .length property too — it works the same way. One subtle difference: in Java .length is a field, not a method, so there are no parentheses. Compare this to String, where you call .length() with parentheses because it is a method.
</aside>
String name = "Alice";
System.out.println(name.length()); // String → method, needs ()
int[] nums = {1, 2, 3};
System.out.println(nums.length); // Array → field, no ()
Assign a new value to a specific index:
String[] cities = {"Amsterdam", "Rotterdam", "Utrecht"};
cities[1] = "Delft"; // replace Rotterdam with Delft
System.out.println(cities[1]); // Delft
ArrayIndexOutOfBoundsExceptionThis is one of the most common runtime errors in Java. It happens when you try to access an index that doesn't exist in the array.
int[] numbers = {10, 20, 30}; // valid indices: 0, 1, 2
System.out.println(numbers[3]); // ❌ ArrayIndexOutOfBoundsException
System.out.println(numbers[-1]); // ❌ ArrayIndexOutOfBoundsException
Java throws this exception at runtime — the code compiles fine, but crashes when it runs.
Always make sure your index stays within 0 to length - 1:
int[] numbers = {10, 20, 30};
// ✅ Safe — the condition guarantees i never reaches numbers.length
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
<aside> 💡
The most common mistake is writing i <= numbers.length instead of i < numbers.length. The last valid index is length - 1, not length.
</aside>
for loopUse when you need the index (e.g. to modify elements or print position):
String[] fruits = {"Apple", "Banana", "Cherry"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(i + ": " + fruits[i]);
}
// 0: Apple
// 1: Banana
// 2: Cherry
for loop (for-each)Use when you only need the values, not the index — cleaner and less error-prone:
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// Apple
// Banana
// Cherry
<aside> 💡
Prefer the enhanced for loop when you don't need the index. It's shorter, avoids off-by-one errors, and reads naturally as "for each fruit in fruits".
</aside>
The type declaration before [] determines what the array can hold. Any Java type works:
int[] scores = {95, 87, 73, 61};
double[] prices = {9.99, 14.50, 3.75};
boolean[] switches = {true, false, true, true};
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
String[] names = {"Alice", "Bob", "Charlie"};
All arrays follow the same rules regardless of type — zero-indexed, fixed size, .length property.
Java arrays are simple and fast, but they come with important constraints:
| Limitation | What it means |
|---|---|
| Fixed size | Once created, an array cannot grow or shrink. new int[5] always has exactly 5 slots. |
| Single type | All elements must be the same type. No mixing int and String. |
| No built-in methods | Arrays have no .push(), .filter(), .map() etc. like JavaScript arrays do. |
| No built-in printing | System.out.println(myArray) prints a memory address, not the contents. |
int[] nums = new int[3];
nums[3] = 99; // ❌ Can't grow — index 3 doesn't exist
<aside> 💡
These limitations are why Java has the Collections framework — classes like ArrayList, HashMap, and others that offer flexible, feature-rich alternatives. You'll cover these in the coming weeks. For now, arrays are the foundation.
</aside>
Arrays Utility ClassJava's java.util.Arrays class provides helpful static methods for working with arrays. You need to import it at the top of your file.
import java.util.Arrays;
Arrays.toString() — print array contents