An array is the first data structure you meet in Java: a fixed-size row of slots, all holding the same type, each reachable instantly by its index. Marks of 60 students, pixels in an image row, daily temperatures for a month — whenever you have "many values of one kind", an array is the simplest way to hold them.
Arrays also dominate fresher coding tests. Reverse an array, find the second largest, count duplicates — these questions assume you are completely fluent in declaring, filling and looping over arrays. This guide builds that fluency.
Declaring and creating arrays
Declaration and creation are separate steps, even when you write them on one line:
int[] marks; // declaration: marks can point to an int array
marks = new int[5]; // creation: allocate 5 slots, all initialized to 0
double[] prices = new double[3]; // {0.0, 0.0, 0.0}
String[] cities = new String[2]; // {null, null}
int[] primes = {2, 3, 5, 7, 11}; // literal: size inferred as 5
Three things to notice. First, the size goes with new, never with the type — int[5] marks is not Java. Second, new fills every slot with the default value of the element
type: 0 for numeric data types, false for boolean,
null for objects. Third, the literal form {2, 3, 5, 7, 11} only works in the same
statement as the declaration.
Java also accepts int marks[] (the C style), but int[] marks is the convention: the
type is "int array", so the brackets belong with the type.
Arrays are objects. The variable marks holds a reference to the array on the heap, not
the array itself — which is why assigning one array variable to another copies the
reference, not the data. Both variables then point at the same array.
Indexing and the length field
Indexes run from 0 to length - 1. The size is available in the length field:
public class IndexBasics {
public static void main(String[] args) {
int[] marks = {72, 85, 64, 91, 78};
System.out.println(marks[0]); // 72 (first)
System.out.println(marks[marks.length - 1]); // 78 (last)
marks[2] = 70; // overwrite the third element
System.out.println(marks[2]); // 70
}
}
Access by index is O(1): the JVM computes the memory offset directly, no scanning needed. That constant-time access is the array's superpower and the reason it underlies ArrayList internally.
Read marks[marks.length - 1] carefully — asking for marks[marks.length] (index 5 in a
5-element array) compiles fine but throws ArrayIndexOutOfBoundsException at runtime.
Common mistake: A common mistake beginners make is confusing the three size accessors: arrays use the field
length, Strings use the methodlength(), and collections usesize(). Writingmarks.length()on an array will not compile. Say it as a rhyme if it helps: array-length, string-length-brackets, list-size.
Iterating over arrays
You will loop over arrays thousands of times in your career, so both idioms from the
Java loops guide must be automatic. The indexed for when you
need positions, for-each when you only need values:
public class MaxFinder {
public static void main(String[] args) {
int[] marks = {72, 85, 64, 91, 78};
// for-each: read every value
int max = marks[0];
for (int m : marks) {
if (m > max) {
max = m;
}
}
System.out.println("Highest mark: " + max); // 91
// indexed for: we need the position too
int maxIndex = 0;
for (int i = 1; i < marks.length; i++) {
if (marks[i] > marks[maxIndex]) {
maxIndex = i;
}
}
System.out.println("Topper is student #" + (maxIndex + 1)); // #4
}
}
The pattern in both halves — start with the first element, compare against the rest using
an if from control statements — is the seed of
half the array questions you will face: max, min, second largest, count above average.
Two-dimensional arrays
A 2D array is an array of arrays — think of a timetable or a matrix of rows and columns:
public class MatrixSum {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0;
for (int i = 0; i < matrix.length; i++) { // rows
for (int j = 0; j < matrix[i].length; j++) { // columns in row i
sum += matrix[i][j];
}
}
System.out.println("Sum of all elements: " + sum); // 45
}
}
matrix.length is the number of rows; matrix[i].length is the number of columns in row
i. Because each row is its own array, rows can have different lengths — a jagged array —
which is why the inner loop asks each row for its own length instead of assuming a fixed
width.
The Arrays utility class
java.util.Arrays provides the operations arrays lack on their own. These five cover most
day-to-day work:
| Method | What it does |
|---|---|
Arrays.toString(arr) |
Readable printout: [72, 85, 64] |
Arrays.sort(arr) |
Sorts in place, ascending |
Arrays.binarySearch(arr, key) |
Fast search — array must be sorted first |
Arrays.copyOf(arr, newLen) |
Copy into a new array of the given size |
Arrays.fill(arr, value) |
Set every slot to one value |
import java.util.Arrays;
public class ArraysDemo {
public static void main(String[] args) {
int[] marks = {72, 85, 64, 91, 78};
Arrays.sort(marks);
System.out.println(Arrays.toString(marks)); // [64, 72, 78, 85, 91]
int pos = Arrays.binarySearch(marks, 85);
System.out.println("85 found at index " + pos); // 3
int[] bigger = Arrays.copyOf(marks, 8);
System.out.println(Arrays.toString(bigger)); // [64, 72, 78, 85, 91, 0, 0, 0]
}
}
Notice how copyOf pads the extra slots with zeros — this copy-into-a-bigger-array trick
is exactly how resizable structures grow, since a created array can never change size.
Pro tip:
Arrays.binarySearchreturns nonsense on an unsorted array — it does not throw an error, it just gives a wrong (often negative) index. Sort first, always. And for comparing two arrays, useArrays.equals(a, b); the==operator only compares references, so two arrays with identical contents still come out "not equal".
Arrays of objects and String[]
Element types are not limited to primitives. The args parameter of main is a String
array, and you can build arrays of your own classes:
String[] batch = {"Anil", "Divya", "Ravi"};
for (String name : batch) {
System.out.println(name.toUpperCase());
}
One trap: new String[3] gives you three null slots, not three empty strings. Calling a
method on an element before assigning it throws a NullPointerException. Fill object
arrays before you use them.
Passing arrays to methods
Java passes everything by value — but for arrays, the value passed is the reference. The method receives a copy of the reference pointing at the same array, so changes to elements inside the method are visible to the caller:
static void applyBonus(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] += 5; // caller sees this change
}
}
Call applyBonus(marks) and the original marks array is modified — there is only one
array in memory. This surprises beginners who expect methods to work on private copies,
and it cuts both ways. It is efficient, because a million-element array is never
duplicated just to be read; and it is dangerous, because a method can silently mutate data
its caller still depends on.
Reassigning the parameter, however, does nothing outside: writing arr = new int[10];
inside the method only repoints the local copy of the reference. The caller's variable
still points at the original array. If a method must not touch the caller's data, hand it
a defensive copy made with Arrays.copyOf — a pattern you will meet again when
encapsulation comes up in OOP.
Array vs ArrayList: when fixed size hurts
The fixed size that makes arrays fast also makes them rigid. Add a sixth student to a
five-slot array and you must allocate a new array and copy — every time. When data grows
and shrinks, reach for a collection instead: an
ArrayList resizes itself and adds rich behaviour like
contains and remove. The trade-offs between the two, and against
LinkedList, matter in interviews, so
learn arrays first — collections make far more sense once you know what they are built on.
Interview note: "Where are arrays stored in Java?" — on the heap, always, even arrays of primitives, because arrays are objects. Expect follow-ups on default values (
new int[5]is all zeros) and on whatarr1 == arr2compares (references, not contents). These three facts together answer most array theory questions.
What to practise next
Fluency comes from repetition, not reading. Work through this ladder: reverse an array in place, find the second largest without sorting, count how many elements exceed the average, rotate an array by k positions, then merge two sorted arrays. Every one of these uses only arrays, loops and if-conditions — and every one has appeared in real fresher screening tests.
At CodeBegun's Java Full Stack course in Hyderabad, this exact ladder is the week-two assignment set, because students who grind through it find collections, strings and even DSA rounds dramatically easier afterwards.
Frequently Asked Questions
How do you declare and initialize an array in Java?
Why do Java arrays start at index 0?
What is the difference between length and length() in Java?
Can you change the size of an array in Java?
What is the difference between an array and an ArrayList?
How do you print a Java array?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — Explore the Program

