Java Arrays — Why <= Crashed 2.4 Million Records
One character difference: < vs <= in array loops.
20+ years shipping production Java in banking & fintech. Written from production experience, not tutorials.
- Java array = fixed-size contiguous memory block holding same-type elements. Accessed by zero-based index: arr[0] first, arr[length-1] last
- Key components: declaration (int[] scores), creation (new int[5]), initialization ({1,2,3}), length property (scores.length)
- Performance: O(1) access via address calculation (base + index * element_size). Sequential iteration is cache-friendly (~10x faster than linked structures)
- Production trap: ArrayIndexOutOfBoundsException caused by using <= instead of < in loop condition — compiles fine, crashes at runtime
- Biggest mistake: Printing array directly — System.out.println(scores) prints memory address [I@6d06d69c, not the contents
Java arrays are fixed-length, zero-indexed containers that store elements of a single type in contiguous memory. They exist because the JVM needs a predictable, cache-friendly data structure for fast random access — O(1) by index — without the overhead of dynamic resizing or boxing.
You create them with new int[10] or the shorthand {1, 2, 3}, but the length is set at creation and never changes. This rigidity is both their strength and their danger: you get raw speed and memory locality, but you must track bounds yourself. Alternatives like ArrayList or LinkedList trade that speed for flexibility, so arrays are best when you know the exact size upfront and need maximum performance — think high-frequency trading systems or embedded JVMs where every nanosecond counts.
The infamous ArrayIndexOutOfBoundsException is the price of that contract, and as the title suggests, a single off-by-one error in a loop can silently corrupt millions of records when writing to a database or file, because Java trusts you to stay within bounds and offers no runtime guardrails beyond the exception itself.
Imagine you're organising a egg carton. Instead of having 12 loose eggs rolling around your kitchen counter, the carton holds all 12 in one neat, numbered container — slot 0 through slot 11. A Java array is exactly that carton: one named container that holds a fixed number of values, all of the same type, each sitting in a numbered slot you can reach instantly. No more juggling 12 separate variables.
A Java array is a fixed-length container that holds elements of a single type, indexed from zero. Without it, you’re manually juggling variables or dragging in heavyweight collections for simple sequential data. Misunderstand the reference model or the bounds, and you’ll face null pointers, silent data corruption, or runtime exceptions. This article covers exactly what an array is, how to walk through it efficiently, and why 2D arrays are just arrays of arrays.
What an Array Actually Is — And How to Create One
An array is a fixed-size, ordered container that holds multiple values of the same data type under a single variable name. 'Fixed-size' is the crucial word here — once you create an array with 5 slots, it has exactly 5 slots forever. You can't shrink it or stretch it later. This is a deliberate design decision: by locking the size upfront, Java can reserve one continuous block of memory, which makes reading and writing values extremely fast.
Every slot in the array has an index — a number that tells you its position. Arrays in Java are zero-indexed, meaning the first slot is index 0, not 1. So a 5-element array has indices 0, 1, 2, 3, and 4. That last index is always length minus one — a detail that trips up almost every beginner at least once.
There are two ways to create an array: declare and allocate separately, or declare and initialise in one shot with values you already know. Both are shown below.
package io.thecodeforge.java.arrays; public class ArrayCreation { public static void main(String[] args) { // --- WAY 1: Declare the array, then fill in the values yourself --- // This creates an integer array with exactly 5 slots. // Right now every slot holds 0 (Java fills numeric arrays with 0 by default). int[] highScores = new int[5]; // Now we assign values to each slot using its index (0-based) highScores[0] = 9500; // first slot highScores[1] = 8750; highScores[2] = 8200; highScores[3] = 7600; highScores[4] = 5100; // fifth (last) slot — index 4, NOT 5 // --- WAY 2: Declare AND initialise in one line --- // Use this when you already know all the values up front. // Java counts the values and sets the size automatically. String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; // Reading a value back: use the variable name + [index] System.out.println("Top score: " + highScores[0]); // prints 9500 System.out.println("Third day: " + daysOfWeek[2]); // prints Wednesday // .length gives you the number of slots (NOT a method call — no parentheses!) System.out.println("Number of days: " + daysOfWeek.length); // prints 5 } }
length, not a method. Write daysOfWeek.length — NOT daysOfWeek.length(). Adding parentheses causes a compile error because length is a field, not a method. Strings, by contrast, use length() WITH parentheses. Yes, it's inconsistent. Welcome to Java.new is just a reference — int[] scores; allocates zero memory. Trying to use it throws NullPointerException.new int[5] allocates 20 bytes (5 ints * 4 bytes) and zero-initialises all slots. This is eager allocation, not lazy.int[1_000_000] allocates 4MB immediately. Validate array size from external input before allocating.array.length - 1. Writing array[array.length] always causes an ArrayIndexOutOfBoundsException.array.length to get size, not a hardcoded number. For loops, condition is i < array.length.Looping Through Arrays — The Right Way to Visit Every Slot
Creating an array is only half the job. The real power comes from being able to do something with every element automatically, without writing repetitive code. That's what loops are for. There are two main approaches in Java, and knowing when to use each one is a sign of a developer who actually understands the tool.
The classic for loop gives you the index at every step. Use this when you need to know the position of each element — for example, when printing 'Rank 1:', 'Rank 2:', etc., or when you need to compare neighbouring elements. The downside is a little more ceremony: you manage a counter variable yourself.
The enhanced for loop (also called the 'for-each' loop) is cleaner. It hands you each value directly, one at a time, without exposing the index. Use this when you simply want to read or process every element and you don't care which position it's in. It's shorter, harder to get wrong, and reads like plain English: 'for each temperature in weeklyTemperatures, do this'.
package io.thecodeforge.java.arrays; public class ArrayIteration { public static void main(String[] args) { double[] weeklyTemperatures = {18.5, 21.0, 19.3, 23.7, 22.1, 17.8, 20.4}; // --- CLASSIC for LOOP --- // Use when you need the INDEX (position) of each element. // i starts at 0 (first slot), runs while i < length (NOT <=), steps by 1. System.out.println("=== Daily Forecast ==="); for (int i = 0; i < weeklyTemperatures.length; i++) { // i is the current index; weeklyTemperatures[i] is the value at that index System.out.println("Day " + (i + 1) + ": " + weeklyTemperatures[i] + "°C"); } // --- ENHANCED for-each LOOP --- // Use when you just want EVERY VALUE and don't need to track position. // Reads as: "for each temperature in weeklyTemperatures" double total = 0; for (double temperature : weeklyTemperatures) { total += temperature; // add each value to the running total } // Calculate and display the weekly average double average = total / weeklyTemperatures.length; System.out.printf("%nWeekly average: %.1f°C%n", average); } }
for loop when you don't actually need i is a subtle code smell — it adds noise and creates an extra variable that could accidentally be misused. The for-each loop signals clearly to anyone reading your code: 'I just need every value, nothing fancy.' Only pull out the index-based loop when the position genuinely matters.for loop when you need the index; use the enhanced for-each loop when you only need the values — it's shorter, safer, and more readable.i <= array.length, it's almost certainly wrong. Use <.Arrays of Arrays — A Quick Look at 2D Arrays
Sometimes one row of data isn't enough. Think of a seating chart for a cinema: you have rows AND seats within each row. Or a spreadsheet: rows and columns. Java handles this with a two-dimensional array — essentially an array whose elements are themselves arrays. Picture the egg carton analogy again, but now imagine a whole box of egg cartons stacked on top of each other. You need two numbers to pinpoint one egg: which carton (row), and which slot within that carton (column).
You declare a 2D array with two sets of square brackets: int[][]. The first index selects the row; the second selects the column within that row. Everything else you already know still applies — zero-based indexing, .length for size, loops for iteration.
2D arrays are genuinely useful: game boards, image pixels (rows and columns of colour values), timetables, and matrix maths all map naturally onto them. You won't need them on day one, but recognising the pattern now means they won't feel foreign when they appear.
package io.thecodeforge.java.arrays; public class CinemaSeatingChart { public static void main(String[] args) { // A cinema with 3 rows, each containing 4 seats. // true = seat is booked, false = seat is available. // Outer array = rows (3 rows), inner arrays = seats per row (4 each). boolean[][] seatBooked = { {true, true, false, true }, // Row 0 (front) {false, false, false, false}, // Row 1 (middle) — all free {true, false, true, true } // Row 2 (back) }; System.out.println("=== Cinema Seat Availability ==="); System.out.println("(O = Available, X = Booked)\n"); // Outer loop walks through each ROW for (int row = 0; row < seatBooked.length; row++) { System.out.print("Row " + (row + 1) + ": "); // Inner loop walks through each SEAT in the current row for (int seat = 0; seat < seatBooked[row].length; seat++) { // Ternary operator: if booked print X, otherwise print O System.out.print(seatBooked[row][seat] ? " X " : " O "); } System.out.println(); // move to next line after each row } // Count total available seats using for-each loops int availableSeats = 0; for (boolean[] row : seatBooked) { // each row for (boolean seat : row) { // each seat in that row if (!seat) availableSeats++; // if NOT booked, count it } } System.out.println("\nAvailable seats: " + availableSeats); } }
seatBooked[0].length could be 4 while seatBooked[1].length is 6. This is called a jagged array. Many interviewers ask about this to see if you understand the underlying structure. Languages like C store true rectangular matrices in memory; Java doesn't — each row is a separate object.int[1000][1000] allocates 1001 objects: one outer + 1000 rows.int size = rows cols; int[] matrix = new int[size]; Access: value = matrix[row cols + col]. This is one object, faster iteration, better cache locality.grid[row].length for inner loop bounds, not grid[0].length (fails on jagged arrays).Passing Arrays to Methods — Why Your Method Just Got a Reference, Not a Copy
Arrays are objects. When you pass an array to a method, you pass a reference to the original array. The method can change the contents. This catches juniors off guard in production. If you want to protect your array from unintended modifications, pass a clone or use System.arraycopy for a shallow copy. For primitive arrays, clone works fine. For object arrays, you need a deep copy if the objects are mutable. The point is: understand that you're sharing the same memory. If you don't want that, make a defensive copy before handing it over. This is why we see bugs like logging services mutating input arrays. Always document whether a method modifies its array parameter.
// io.thecodeforge public class PassingArrays { public static void main(String[] args) { int[] scores = {95, 87, 73}; System.out.println("Before: " + java.util.Arrays.toString(scores)); modifyArray(scores); System.out.println("After: " + java.util.Arrays.toString(scores)); } static void modifyArray(int[] arr) { arr[0] = 99; // changes original array! } }
array.clone() or Arrays.copyOf().Returning an Array from a Method — Don't Expose Internal State
When you return an array from a method, you are returning a reference to the same array. If that array is an internal field of your class, callers can modify your class's state. This is a design flaw. In Spring Boot services, we often return data transfer objects (DTOs), but if you're returning an array directly from a repository or a service, make a copy. The caller gets what they need; your internal state stays safe. Use Arrays.copyOf or System.arraycopy for primitives. For objects, consider returning an unmodifiable list or a defensive copy. This avoids Heisenbugs where a caller mutates the array and breaks other parts of your service. The rule is simple: never return the same reference to your internal array.
// io.thecodeforge public class ReturningArrays { private int[] internalData = {10, 20, 30}; public int[] getDataUnsafe() { return internalData; // caller can mutate! } public int[] getDataSafe() { return java.util.Arrays.copyOf(internalData, internalData.length); } public static void main(String[] args) { ReturningArrays obj = new ReturningArrays(); int[] bad = obj.getDataUnsafe(); bad[0] = 999; System.out.println(obj.internalData[0]); // prints 999 — bug! } }
Arrays.copyOf() or Collections.unmodifiableList().The Arrays Utility Class — Stop Writing Boilerplate, Use These Static Methods
Java's java.util.Arrays class is your best friend. It provides static methods for sorting, searching, comparing, filling, and converting arrays. In production, you'll use Arrays.toString() for debugging, Arrays.sort() for quick ordering, Arrays.binarySearch() for fast lookups on sorted arrays, and Arrays.equals() for comparing contents. For copying, use Arrays.copyOf() or Arrays.copyOfRange(). These are optimized and handle edge cases better than manual loops. For example, Arrays.fill() initializes all elements to a default value in one line. Do not write your own sort. Do not loop to print an array. Use the utility class. It's been battle-tested since Java 1.2 and is a core part of the Spring Boot ecosystem.
// io.thecodeforge import java.util.Arrays; public class ArraysUtility { public static void main(String[] args) { int[] numbers = {5, 3, 8, 1, 2}; // Print System.out.println("Original: " + Arrays.toString(numbers)); // Sort Arrays.sort(numbers); System.out.println("Sorted: " + Arrays.toString(numbers)); // Search (binarySearch requires sorted array) int index = Arrays.binarySearch(numbers, 3); System.out.println("Index of 3: " + index); // Fill Arrays.fill(numbers, 0); System.out.println("Filled: " + Arrays.toString(numbers)); // Compare int[] other = {0, 0, 0, 0, 0}; System.out.println("Equals: " + Arrays.equals(numbers, other)); } }
Arrays.asList() with primitive arrays directly — it wraps the array as a list, not the elements. Use Arrays.stream().boxed().collect(Collectors.toList()) instead.The Off-by-One That Corrupted 2.4 Million Customer Records
i <= array.length was correct because 'i should go up to the length'. They didn't realise the last valid index is length - 1. The loop condition should be i < array.length. The dev environment had 10 customers, and the exception was caught by the test harness, so the team never saw the rollback in testing.for (int i = 0; i <= customers.length; i++). For an array of length 2.4 million, the loop iterates i = 0 to 2,400,000. The last iteration tries to access customers[2400000], which does not exist (valid indexes are 0 to 2,399,999). The exception occurred after processing the 2.4 millionth record, so all preceding records were already processed but not yet committed. The error handler caught the exception and called transaction.rollback(), discarding all work. One character (<= vs <) caused 8 hours of reprocessing.for (int i = 0; i < customers.length; i++).
2. Added unit test that verifies the loop never accesses index == length.
3. For production batch jobs, use atomic commit after each batch of 1000 records, not a single transaction for the entire job. This limits rollback scope.
4. Added assertion at loop start: assert i < customers.length : 'Index out of bounds at ' + i; in debug builds.
5. Enabled -ea (enable assertions) in CI to catch off-by-one errors before production.- The boundary between 'works' and 'crashes' in array code is a single character: < vs <=. Always use i < array.length.
- A failing transaction that rolls back after processing all records is devastating for batch jobs. Commit periodically, not just at the end.
- ArrayIndexOutOfBoundsException is a runtime exception. The code compiles fine. The bug only appears when the last iteration runs.
- Always test loops with the smallest possible array (size 1) to verify boundary conditions. A 1-element array crashes immediately if you use <=.
for (int i = 0; i <= arr.length; i++) is always wrong. Fix to <. Also check manual index calculations: int lastIndex = arr.length; arr[lastIndex] = value; — last index should be arr.length - 1.index - 1 when index is 0, or binarySearch result that's negative and used directly. Validate index before access: if (idx >= 0 && idx < arr.length) { ... }int[] arr = new int[]{1,2,3}; or loop to fill.Arrays.toString(arr) for 1D arrays, Arrays.deepToString(arr) for 2D arrays. Add import java.util.Arrays; at top.new int[size]. Declaration alone (int[] arr;) does not create the array. Add arr = new int[10]; before access.grep -n 'for.*<=' src/**/*.javagrep -n 'for.*>=' src/**/*.javai <= arr.length to i < arr.length. For reverse loops, i >= 0 is correct for the lower bound.grep -n 'System.out.println.*\[\]' src/**/*.javagrep -n 'System.out.println.*[a-z]\[' src/**/*.javaSystem.out.println(arr) with System.out.println(Arrays.toString(arr)). Add import java.util.Arrays;grep -n 'new int\[.*\]' src/**/*.java | grep -v '= {\|Arrays.fill'grep -n 'int\[\].*=.*new' src/**/*.javaint[] arr = {1,2,3}; or fill in loop: for (int i = 0; i < arr.length; i++) arr[i] = i;grep -n 'int\[\]\s\+\w\+\s*;' src/**/*.java | grep -v '='grep -n 'arr\[' src/**/*.java | grep -v 'new int\['int[] arr = new int[10]; not just int[] arr;. For field arrays, initialize in constructor or declaration.grep -n 'grid\[0\]\.length' src/**/*.javagrep -A5 'for.*int.*row' src/**/*.java | grep 'grid\['for (int col = 0; col < grid[row].length; col++). Each row may have different length (jagged array).| Feature | Classic for Loop | Enhanced for-each Loop |
|---|---|---|
| Access to index | Yes — you control the counter variable i | No — index is hidden from you |
| Syntax complexity | More verbose — init, condition, increment | Minimal — just 'for (type var : array)' |
| Risk of off-by-one error | Higher — easy to write i <= length by mistake | None — Java handles boundaries automatically |
| Can modify array elements | Yes — use index to write back: array[i] = newVal | No — modifying the loop variable doesn't change the array |
| Best used when | You need position, reverse traversal, or skipping elements | You just want to read or process every element in order |
| Readability | Lower for simple reads — more noise | Higher — reads like natural language |
| Performance | Same as for-each (compiler generates same bytecode for arrays) | Same — no overhead difference |
Key takeaways
array.length - 1. Writing array[array.length] always causes an ArrayIndexOutOfBoundsException.for loop when you need the index; use the enhanced for-each loop when you only need the valuesSystem.out.println() directlyArrays.toString() for 1D arrays or Arrays.deepToString() for 2D arrays.Common mistakes to avoid
5 patternsArrayIndexOutOfBoundsException from using <= instead of <
ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. This happens because a 5-element array's last valid index is 4, not 5.i < array.length, never i <= array.length. Read it aloud: 'while i is less than the length' — the moment i equals the length, you've gone one step too far.Printing an array with System.out.println() and getting garbage output
System.out.println(scores) expecting to see [95, 87, 76] but instead seeing something like [I@6d06d69c. That cryptic string is the array's memory address, not its contents.Arrays.toString(scores) for a 1D array, or Arrays.deepToString(grid) for a 2D array. Both are in java.util.Arrays — add import java.util.Arrays; at the top of your file.Trying to resize an array after creation
int[] basket = new int[3], fill it up, then try to add a fourth item and it simply won't fit — there's no basket.add() method because arrays don't have one.ArrayList<Integer> instead. Arrays are the right choice when the size is known and fixed; ArrayList is the right choice when it isn't.Treating array names as values that can be reassigned to change size
int[] arr = new int[3]; arr = new int[5]; — This works, but it creates a new array, abandoning the old one. The original 3 elements are lost.System.arraycopy() or Arrays.copyOf(). Better to use ArrayList.Accessing array elements before initialization
int[] arr; arr[0] = 5; throws NullPointerException. The array reference is null because no array was created.int[] arr = new int[10]; before accessing elements. Declaration alone does not allocate memory.Interview Questions on This Topic
What is the difference between an array and an ArrayList in Java, and when would you choose one over the other?
add(), remove(), contains(), (3) you're working with generics or APIs that expect Collection. ArrayList's growth factor is 1.5x (doubling in older versions), which causes occasional O(n) copy operations. Arrays are slightly faster for iteration and access due to no method call overhead, but for most use cases, ArrayList is the right default.If I declare `int[] numbers = new int[10]`, what value does `numbers[5]` hold before I assign anything to it, and why?
numbers[5] holds 0. Java always initializes array elements to default values for the type: 0 for int, 0.0 for double, false for boolean, null for objects. This is a safety feature inherited from C's calloc. It ensures you never read random memory garbage, which in C would be undefined behavior. For local variables, Java requires explicit initialization before use, but array elements are treated differently — they are guaranteed to be initialized to default values immediately when the array is created with new. This is why numbers[5] returns 0 even if you never assigned to it. However, for the array variable itself (numbers is not null because you created it with new).How would you find the second-largest value in an integer array without sorting it — walk me through your logic step by step.
largest and secondLargest. Initialize largest = Integer.MIN_VALUE and secondLargest = Integer.MIN_VALUE. For each element: if element > largest, set secondLargest = largest, then largest = element. Else if element > secondLargest and element != largest, set secondLargest = element. After the loop, secondLargest holds the answer. Edge cases: if array has fewer than 2 elements, throw exception. If all elements are identical, you need to decide if second largest is the same value (then return that value) or there is none (throw exception). This is O(n) time, O(1) space. Sorting would be O(n log n) and require additional memory. The key is to update second largest only when we find a new candidate that is not equal to the largest (if duplicates allowed).What is the time complexity of accessing an array element by index in Java? Why?
base_address + (index * element_size). This is a single arithmetic operation (addition and multiplication) that takes the same amount of time regardless of the array size. For an int array, element_size = 4 bytes. So arr[1000] is computed as base + 4000. For an object array (String[]), element_size = 8 bytes (reference size on 64-bit compressed oops). This is true for all arrays regardless of length. Contrast with linked list, where access is O(n) because you must traverse from the head to the target position. This constant-time access is the primary reason arrays are used for performance-critical applications like image processing, game engines, and database buffers.Frequently Asked Questions
It depends on the data type. Numeric arrays (int, double, etc.) default to 0. Boolean arrays default to false. Object arrays — including String[] — default to null. Java always initialises array slots to these safe defaults so you never read random memory garbage the way you might in C.
Not directly. Every element must be the same type as declared — an int[] can only hold integers. However, if you declare an array of type Object[], you can technically store anything in it since every Java class extends Object. In practice this is considered bad design; use a class or a collection like ArrayList<Object> if you genuinely need mixed types.
They are functionally identical — both declare an integer array. The int[] numbers style is strongly preferred in Java because the type information (int[]) stays together, making it immediately clear that numbers is an array. The int numbers[] syntax is a leftover from C-style conventions and is considered outdated in Java code.
You cannot resize an existing array. The size is fixed at creation. To achieve a resizable effect, create a new array with the desired size and copy elements using System.arraycopy() or Arrays.copyOf(). The old array will be eligible for garbage collection. For most cases, ArrayList handles this automatically with its dynamic resizing strategy (doubling capacity, copying internally). Example: int[] newArr = Arrays.copyOf(oldArr, newSize);
20+ years shipping production Java in banking & fintech. Written from production experience, not tutorials.
That's Arrays. Mark it forged?
4 min read · try the examples if you haven't