Java Arrays — Why <= Crashed 2.4 Million Records
One character difference: < vs <= in array loops.
- 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
Every real program deals with collections of data. A music app stores hundreds of song titles. A weather app tracks 30 days of temperatures. A quiz game holds 10 questions. If Java didn't give you a way to group related values together, you'd have to write String song1, String song2, String song3... all the way to String song500. That's not programming — that's chaos. Arrays are Java's first and most fundamental answer to this problem, and they're built directly into the language itself, which means they're blazing fast and available everywhere.
But arrays have sharp edges. The size is fixed forever — you can't add a sixth day to a String[5] weekdays array. There's no built-in bounds checking at runtime beyond the exception. An int[10] array has indexes 0..9, and arr[10] will crash. And printing an array directly gives you a memory address, not the values. Understanding these limitations is what separates a developer who uses arrays from one who understands them.
By the end you'll know how to declare and initialize arrays, loop through them correctly, work with 2D arrays, and avoid the off-by-one and printing traps that catch every beginner.
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.
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'.
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.
| 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
- Arrays are zero-indexed — the first element is always at index 0 and the last is at index
array.length - 1. Writingarray[array.length]always causes an ArrayIndexOutOfBoundsException. - An array's size is fixed at creation time and cannot change. If you need a resizable collection, reach for ArrayList instead.
- Use the classic
forloop when you need the index; use the enhanced for-each loop when you only need the values — it's shorter, safer, and more readable. - Never print an array with
System.out.println()directly — you'll get a memory address. Always useArrays.toString()for 1D arrays orArrays.deepToString()for 2D arrays. - Array defaults: numeric → 0, boolean → false, object → null. Local array variables are initialized to these defaults, unlike local primitive variables which require explicit initialization.
Common Mistakes to Avoid
- ArrayIndexOutOfBoundsException from using <= instead of <
Symptom: Program crashes at runtime with `ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5`. This happens because a 5-element array's last valid index is 4, not 5.
Fix: Always writei < array.length, neveri <= 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
Symptom: Writing `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.
Fix: UseArrays.toString(scores)for a 1D array, orArrays.deepToString(grid)for a 2D array. Both are injava.util.Arrays— addimport java.util.Arrays;at the top of your file. - Trying to resize an array after creation
Symptom: You create `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.
Fix: If your collection needs to grow or shrink dynamically, use anArrayList<Integer>instead. Arrays are the right choice when the size is known and fixed;ArrayListis the right choice when it isn't. - Treating array names as values that can be reassigned to change size
Symptom: `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.
Fix: This reassigns the reference, not resizes. For resizing, you must copy elements manually usingSystem.arraycopy()orArrays.copyOf(). Better to use ArrayList. - Accessing array elements before initialization
Symptom: `int[] arr; arr[0] = 5;` throws NullPointerException. The array reference is null because no array was created.
Fix: Always create the array:int[] arr = new int[10];before accessing elements. Declaration alone does not allocate memory.
Interview Questions on This Topic
- QWhat is the difference between an array and an ArrayList in Java, and when would you choose one over the other?Mid-levelReveal
- QIf I declare
int[] numbers = new int[10], what value doesnumbers[5]hold before I assign anything to it, and why?JuniorReveal - QHow would you find the second-largest value in an integer array without sorting it — walk me through your logic step by step.Mid-levelReveal
- QWhat is the time complexity of accessing an array element by index in Java? Why?JuniorReveal
Frequently Asked Questions
What is the default value of an array element in Java?
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.
Can a Java array hold different data types at the same time?
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.
What is the difference between `int[] numbers` and `int numbers[]` in Java?
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.
How do I resize an array in Java?
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);
That's Arrays. Mark it forged?
3 min read · try the examples if you haven't