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
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.
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'.
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.
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.
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.
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.
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.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.Frequently Asked Questions
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