Beginner 3 min · March 05, 2026

Java Arrays — Why <= Crashed 2.4 Million Records

One character difference: < vs <= in array loops.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
Quick Answer
  • 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.

Java Array Loops Compared
FeatureClassic for LoopEnhanced for-each Loop
Access to indexYes — you control the counter variable iNo — index is hidden from you
Syntax complexityMore verbose — init, condition, incrementMinimal — just 'for (type var : array)'
Risk of off-by-one errorHigher — easy to write i <= length by mistakeNone — Java handles boundaries automatically
Can modify array elementsYes — use index to write back: array[i] = newValNo — modifying the loop variable doesn't change the array
Best used whenYou need position, reverse traversal, or skipping elementsYou just want to read or process every element in order
ReadabilityLower for simple reads — more noiseHigher — reads like natural language
PerformanceSame 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. Writing array[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 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.
  • Never print an array with System.out.println() directly — you'll get a memory address. Always use Arrays.toString() for 1D arrays or Arrays.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 write 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
    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: Use 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
    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 an 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
    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 using System.arraycopy() or Arrays.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
    An array has a fixed size set at creation and cannot change. ArrayList is a resizable wrapper (backed by an array) that grows automatically when capacity is exceeded. Choose an array when: (1) the size is known and fixed (e.g., days of week, RGB channels), (2) performance is critical (primitive arrays avoid boxing overhead), (3) you need a multi-dimensional fixed-size grid. Choose ArrayList when: (1) the size is unknown or changes over time, (2) you need convenient methods like 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.
  • QIf I declare int[] numbers = new int[10], what value does numbers[5] hold before I assign anything to it, and why?JuniorReveal
    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).
  • 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
    Traverse the array once, maintaining two variables: 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).
  • QWhat is the time complexity of accessing an array element by index in Java? Why?JuniorReveal
    O(1) constant time. Arrays are stored in contiguous memory. The JVM calculates the memory address as 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

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

Previous
Labeled break and continue in Java
1 / 8 · Arrays
Next
Multi-dimensional Arrays in Java