Java Tutorial
🔍

Java Arrays

Java Arrays

Every program works with groups of related data — a list of student marks, a set of product prices, a collection of employee names. Java's most fundamental way to store a fixed-size group of same-type values is an array.

An array is a single variable that holds multiple values of the same type, arranged in a numbered sequence. Instead of declaring int mark1, int mark2, int mark3 ... int mark50 for fifty students, you declare int[] marks and store all fifty values in one place. Each value is accessed by its position number — called an index — starting from zero.

What Is an Array?

An array is a fixed-size, ordered collection of elements of the same data type stored in contiguous memory locations. Once created, its size cannot change.

An int array of size 5:

  Index:  [  0  ] [  1  ] [  2  ] [  3  ] [  4  ]
  Value:  [ 85  ] [ 90  ] [ 78  ] [ 95  ] [ 88  ]
             ↑
           marks[0] = 85
           marks[1] = 90
           marks[3] = 95

Key points:
  — Index starts at 0 (not 1)
  — Last valid index = length - 1
  — All elements must be the same type
  — Size is fixed at creation time

Declaring and Creating Arrays

There are three ways to create an array in Java. Understanding all three prevents confusion when reading code written by others.

// File: ArrayCreationDemo.java import java.util.Arrays; public class ArrayCreationDemo { public static void main(String[] args) { // Way 1 — declare size, fill later // JVM fills with default values: 0 for int, null for String int[] marks = new int[5]; marks[0] = 85; marks[1] = 90; marks[2] = 78; marks[3] = 95; marks[4] = 88; System.out.println("Way 1 — fill later : " + Arrays.toString(marks)); // Way 2 — declare and initialise in one line (array initialiser) String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; System.out.println("Way 2 — initialiser : " + Arrays.toString(days)); // Way 3 — new keyword with inline values double[] prices = new double[]{499.0, 1299.0, 2499.0, 899.0}; System.out.println("Way 3 — new + values : " + Arrays.toString(prices)); // Default values when size is declared but not filled int[] intDefaults = new int[3]; double[] doubleDefaults = new double[3]; boolean[] boolDefaults = new boolean[3]; String[] strDefaults = new String[3]; System.out.println("\nDefault values:"); System.out.println("int defaults: " + Arrays.toString(intDefaults)); System.out.println("double defaults: " + Arrays.toString(doubleDefaults)); System.out.println("boolean defaults: " + Arrays.toString(boolDefaults)); System.out.println("String defaults : " + Arrays.toString(strDefaults)); } }
Output:
Way 1 — fill later    : [85, 90, 78, 95, 88]
Way 2 — initialiser   : [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Way 3 — new + values  : [499.0, 1299.0, 2499.0, 899.0]

Default values:
int    defaults: [0, 0, 0]
double defaults: [0.0, 0.0, 0.0]
boolean defaults: [false, false, false]
String defaults : [null, null, null]

When you declare new int[5], the JVM allocates five integer slots and fills each with 0. For String[], it fills with null. Knowing default values prevents the common mistake of reading an array element before setting it and wondering why you get 0 or null.

Accessing and Modifying Elements

Array elements are accessed using their index inside square brackets. The index must be a non-negative integer between 0 and array.length - 1.

// File: ArrayAccessDemo.java public class ArrayAccessDemo { public static void main(String[] args) { String[] topCities = {"Mumbai", "Delhi", "Bengaluru", "Chennai", "Hyderabad"}; // Reading elements by index System.out.println("First city : " + topCities[0]); System.out.println("Last city : " + topCities[topCities.length - 1]); System.out.println("Array length: " + topCities.length); // Modifying an element topCities[2] = "Bangalore"; // update Bengaluru to Bangalore System.out.println("After update: " + topCities[2]); // Accessing with a variable index int index = 3; System.out.println("City at index " + index + ": " + topCities[index]); System.out.println(); // What happens with an invalid index try { System.out.println(topCities[10]); // index 10 does not exist } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: " + e.getMessage()); } try { System.out.println(topCities[-1]); // negative index invalid } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: " + e.getMessage()); } } }
Output:
First city  : Mumbai
Last city   : Hyderabad
Array length: 5
After update: Bangalore
City at index 3: Chennai

Error: Index 10 out of bounds for length 5
Error: Index -1 out of bounds for length 5

array.length — note: no parentheses — is a field, not a method. It always equals the number of slots the array was created with. The last valid index is always array.length - 1. Any index outside this range throws ArrayIndexOutOfBoundsException at runtime.

Traversing Arrays

Traversal means visiting every element in order. Java gives you three ways to loop through an array.

// File: ArrayTraversalDemo.java public class ArrayTraversalDemo { public static void main(String[] args) { int[] scores = {72, 88, 91, 65, 78, 95, 83}; // Method 1 — traditional for loop // Use when you need the index inside the loop System.out.println("Traditional for loop:"); for (int i = 0; i < scores.length; i++) { System.out.println(" scores[" + i + "] = " + scores[i]); } System.out.println(); // Method 2 — enhanced for loop (for-each) // Cleaner when you only need the value, not the index System.out.println("Enhanced for-each:"); int total = 0; for (int score : scores) { total += score; } System.out.println(" Total = " + total); System.out.printf(" Average = %.2f%n", (double) total / scores.length); System.out.println(); // Method 3 — while loop // Useful when the stopping condition is more complex System.out.println("While loop (stop at first score above 90):"); int i = 0; while (i < scores.length) { if (scores[i] > 90) { System.out.println(" Found score > 90 at index " + i + ": " + scores[i]); break; } i++; } } }
Output:
Traditional for loop:
  scores[0] = 72
  scores[1] = 88
  scores[2] = 91
  scores[3] = 65
  scores[4] = 78
  scores[5] = 95
  scores[6] = 83

Enhanced for-each:
  Total = 572
  Average = 81.71

While loop (stop at first score above 90):
  Found score > 90 at index 2: 91

The for-each loop is the cleanest and safest traversal — no index management, no off-by-one errors. Use the traditional for loop when you need to know the index — for printing position numbers, skipping elements, or modifying elements at specific positions.

Common Array Operations

// File: ArrayOperationsDemo.java import java.util.Arrays; public class ArrayOperationsDemo { public static void main(String[] args) { int[] marks = {55, 90, 72, 88, 61, 95, 78, 83}; // 1 — Find maximum int max = marks[0]; for (int mark : marks) { if (mark > max) max = mark; } System.out.println("Maximum mark: " + max); // 2 — Find minimum int min = marks[0]; for (int mark : marks) { if (mark < min) min = mark; } System.out.println("Minimum mark: " + min); // 3 — Calculate sum and average int sum = 0; for (int mark : marks) sum += mark; System.out.printf("Sum: %d | Average: %.2f%n", sum, (double) sum / marks.length); // 4 — Count elements meeting a condition int passCount = 0; for (int mark : marks) { if (mark >= 60) passCount++; } System.out.println("Students passed (>=60): " + passCount); // 5 — Search for a specific value (linear search) int target = 88; int foundAt = -1; for (int i = 0; i < marks.length; i++) { if (marks[i] == target) { foundAt = i; break; } } System.out.println("Mark " + target + " found at index: " + foundAt); // 6 — Sort using Arrays.sort() int[] copy = Arrays.copyOf(marks, marks.length); Arrays.sort(copy); System.out.println("Sorted : " + Arrays.toString(copy)); System.out.println("Original: " + Arrays.toString(marks)); // unchanged // 7 — Copy using Arrays.copyOf() int[] firstFour = Arrays.copyOf(marks, 4); System.out.println("First 4 : " + Arrays.toString(firstFour)); // 8 — Fill with a value int[] blanks = new int[5]; Arrays.fill(blanks, 99); System.out.println("Filled : " + Arrays.toString(blanks)); } }
Output:
Maximum mark: 95
Minimum mark: 55
Sum: 622 | Average: 77.75
Students passed (>=60): 7
Mark 88 found at index: 3
Sorted  : [55, 61, 72, 78, 83, 88, 90, 95]
Original: [55, 90, 72, 88, 61, 95, 78, 83]
Maximum mark: 95
Minimum mark: 55
Sum: 622 | Average: 77.75
Students passed (>=60): 7
Mark 88 found at index: 3
Sorted  : [55, 61, 72, 78, 83, 88, 90, 95]
Original: [55, 90, 72, 88, 61, 95, 78, 83]
First 4 : [55, 90, 72, 88]
Filled  : [99, 99, 99, 99, 99]

Arrays.sort() modifies the original array in place. If you need to sort without changing the original, copy it first with Arrays.copyOf() — as shown above.

Array vs ArrayList — When to Use Which

AspectArray int[] / String[]ArrayList ArrayList<Integer>
SizeFixed at creation — cannot grow or shrinkDynamic — grows and shrinks automatically
TypePrimitives and objects both workObjects only (use wrapper: Integer, Double)
Syntaxarr[i] for accesslist.get(i) for access
Add elementNot possible after creationlist.add(value)
Remove elementNot possible — overwrite with defaultlist.remove(index)
SortingArrays.sort(arr)Collections.sort(list)
MemoryLess overhead — raw arrayMore overhead — object wrapper
PerformanceFaster — direct memory accessSlightly slower — method calls
Iterationfor, for-each, whilefor, for-each, Iterator, stream
When to useKnown size, performance-critical, primitive dataUnknown or changing size, need add/remove

Basic Example

public class Main { public static void main(String[] args) { int[] marks = {85, 92, 67, 78, 95}; int total = 0; int max = marks[0]; for (int mark : marks) { total += mark; if (mark > max) { max = mark; } } double average = (double) total / marks.length; System.out.println("Total : " + total); System.out.printf("Average: %.2f%n", average); System.out.println("Highest: " + max); } }

Output

Total  : 417
Average: 83.40
Highest: 95
  1. ›marks is an array holding five int values — one variable representing the whole group of scores.
  2. ›The for-each loop visits every element in order, adding each one to total and updating max whenever a larger value is found.
  3. ›average divides the total by marks.length, so the calculation always stays correct even if the array's size changes later.
  4. ›This is the pattern behind almost every array-processing program: loop once, accumulate a running answer as you go.

Best Practices

Always use array.length in loop conditions — never a hardcoded number. Writing for (int i = 0; i < 5; i++) breaks the moment the array size changes. for (int i = 0; i < marks.length; i++) always works correctly regardless of how many elements are in the array.

Check the length before accessing the first or last element. marks[0] on an empty array throws ArrayIndexOutOfBoundsException. Before writing max = arr[0], verify arr.length > 0. This single check prevents the most common array crash in beginner code.

Use the for-each loop when you only need values. for (int mark : marks) is shorter, cleaner, and impossible to get the index wrong — because there is no index to manage. Switch to the indexed for loop only when you genuinely need the index — for position tracking, modifying elements, or printing "element number N".

Never hardcode array sizes outside the declaration. The size of an array should live in exactly one place — the declaration or the constant that controls it. Using the magic number 7 scattered through a program that processes a week of data breaks silently when the data changes to include 8 days.

Common Mistakes

Mistake 1 — ArrayIndexOutOfBoundsException From Off-by-One

int[] scores = {10, 20, 30, 40, 50}; // Wrong — loops to index 5, but last valid index is 4 for (int i = 0; i <= scores.length; i++) { System.out.println(scores[i]); // throws at i=5 } // Correct — strict less than for (int i = 0; i < scores.length; i++) { System.out.println(scores[i]); }

Mistake 2 — Printing an Array Directly

int[] prices = {299, 599, 999}; System.out.println(prices); // prints [I@7852e922 — useless reference // Correct — use Arrays.toString() import java.util.Arrays; System.out.println(Arrays.toString(prices)); // [299, 599, 999]

An array does not override toString(). Printing it directly gives the type code and memory address. Always use Arrays.toString(array) for readable output.

Mistake 3 — Confusing length (field) With length() (method)

int[] numbers = {1, 2, 3, 4, 5}; String name = "Priya"; System.out.println(numbers.length); // CORRECT — field, no parentheses System.out.println(name.length()); // CORRECT — String method, parentheses System.out.println(numbers.length()); // COMPILE ERROR — arrays have no length() method System.out.println(name.length); // COMPILE ERROR — String has no length field

Mistake 4 — Trying to Resize an Array

int[] items = new int[3]; items[0] = 10; items[1] = 20; items[2] = 30; // Cannot add a 4th element — array is full items[3] = 40; // ArrayIndexOutOfBoundsException // Fix — create a new larger array and copy int[] bigger = new int[5]; System.arraycopy(items, 0, bigger, 0, items.length); bigger[3] = 40; bigger[4] = 50; // Or use ArrayList which resizes automatically

Interview Questions

Q1. What is an array in Java and what are its key characteristics?

An array is a fixed-size, ordered collection of elements of the same data type stored in contiguous memory. Once created, its size cannot change. Elements are accessed by a zero-based integer index — the first element is at index 0, the last at array.length - 1. Arrays can hold primitives (int[], double[]) as well as objects (String[], custom classes). Accessing an index outside the valid range throws ArrayIndexOutOfBoundsException at runtime.

Q2. What is the default value of array elements in Java?

The JVM initialises every array element to its type's default value. For int, short, byte, and long, the default is 0. For double and float, it is 0.0. For boolean, it is false. For char, it is the null character '\u0000'. For any reference type — String, objects — it is null. This automatic initialisation prevents reading garbage memory values but means checking for null before using object array elements is important.

Q3. What is the difference between array length and String length()?

For arrays, length is a final field — no parentheses: arr.length. It holds the number of elements the array was created with. For String, length() is a method — with parentheses: str.length(). It returns the number of characters in the string. Using parentheses on an array (arr.length()) or omitting them on a String (str.length) causes a compile error. This distinction trips up most beginners at least once.

Q4. What is ArrayIndexOutOfBoundsException and what causes it?

ArrayIndexOutOfBoundsException is a runtime exception thrown when code tries to access an array element at an invalid index — either negative or greater than or equal to the array's length. The most common causes are: using <= instead of < in a loop condition (i <= arr.length accesses one index past the end); hardcoding a size that has changed; accessing arr[0] on an empty array; or computing an index incorrectly. The fix is always to verify the index is within 0 to arr.length - 1.

Q5. What is the difference between Array and ArrayList in Java?

An array has a fixed size set at creation — elements cannot be added or removed, only modified. An ArrayList grows and shrinks automatically as elements are added or removed. Arrays can hold both primitives and objects directly. ArrayList can only hold objects — primitives must be wrapped (Integer, Double). Arrays have direct element access via arr[i]; ArrayList uses list.get(i). Arrays are faster and use less memory for fixed-size data. ArrayList is more flexible for collections that grow or shrink.

Q6. How do you copy an array in Java?

Three common ways: Arrays.copyOf(original, newLength) creates a new array with the specified length, copying elements from the original; System.arraycopy(src, srcPos, dest, destPos, length) copies elements between arrays with fine-grained control over positions; and Arrays.copyOfRange(original, from, to) copies a slice. The assignment int[] b = a does NOT copy — it makes b point to the same array as a. Mutating b will change a too.

FAQs

Can an array hold elements of different types?

No — a typed array (int[], String[]) can only hold elements of its declared type. However, Object[] can hold any type of object since every class extends Object. In practice, mixing types in an array is poor design — use a class or record to group related but differently-typed values.

What is the maximum size of an array in Java?

The theoretical maximum is Integer.MAX_VALUE — about 2.1 billion elements. In practice, the limit is the available JVM heap memory. Trying to allocate an array too large for the heap throws OutOfMemoryError. For most programs, arrays with a few thousand to a few million elements are well within limits.

Is the length of an array fixed after creation?

Yes. Once created with new int[5], the array always has exactly 5 slots. You can modify the values in those slots, but you cannot add a 6th slot. If you need more capacity, create a new larger array, copy the elements using System.arraycopy() or Arrays.copyOf(), and discard the old array. ArrayList handles this automatically — it is the right choice when the size varies.

Can you have an array of arrays in Java?

Yes — this is called a two-dimensional array (2D array). int[][] grid = new int[3][4] creates 3 rows of 4 integers each. Each row is itself an array accessible with grid[0], grid[1], etc. Individual elements are accessed with grid[row][col]. Java also supports jagged arrays where each row can have a different length.

Does Arrays.sort() modify the original array?

Yes. Arrays.sort(arr) sorts the elements of arr in place — the original array is modified. If you need the sorted order without changing the original, use int[] copy = Arrays.copyOf(arr, arr.length) first, then sort the copy.

Summary

An array is Java's foundation for working with fixed-size groups of same-type data. Declare it with the type and [], create it with new Type[size] or an initialiser, access elements with zero-based indices, and always loop with arr.length rather than a hardcoded number.

The two habits that prevent the most common array bugs: check arr.length > 0 before reading the first element, and use arr.length - 1 for the last element rather than counting manually. When the size needs to change at runtime — adding or removing items — ArrayList is the right choice over an array.

For interviews, be ready to explain default values, the difference between length field and length() method, why System.out.println(array) gives a useless output, and how to correctly copy an array without accidentally sharing the reference.

What to Read Next

Practice Programs

Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.

Show all 38 practice programs ↓
Arraysbeginner
Count Zeros in an Array

Counts how many zero values appear in an array.

Arraysintermediate
Find Duplicate Elements

Finds every element that appears more than once in an array.

Arraysintermediate
Find Missing Number

Finds the single missing number from a sequence of 1 to n.

Arraysintermediate
Find Repeated Number

Finds the single number that repeats in an array of n + 1 values from 1 to n.

Arraysintermediate
Find Unique Element

Finds the single element that appears once while every other element appears exactly twice.

Arraysadvanced
Find Majority Element in an Array

Finds the element that appears more than half the time in an array.

Arraysintermediate
Find Least Frequent Element

Finds the element that appears least often in an array.

Arraysintermediate
Find Leaders in an Array

Finds every element that is greater than all the elements to its right.

Arraysintermediate
Find Equilibrium Index

Finds the index where the sum of elements to its left equals the sum to its right.

Arraysintermediate
Find Peak Element in an Array

Finds an element that is greater than both of its neighbors.

Arraysintermediate
Find Local Minimum in an Array

Finds an element that is smaller than both of its neighbors.

Arraysadvanced
Find Longest Consecutive Sequence

Finds the length of the longest run of consecutive integers in an unsorted array.

Arraysintermediate
Find Maximum Difference Between Two Elements

Finds the largest value obtainable by subtracting an earlier element from a later one.

Arraysintermediate
Find Minimum Difference Between Two Elements

Finds the smallest absolute difference between any two elements in an array.

Arraysadvanced
Find Maximum Subarray Sum (Kadane's Algorithm)

Finds the largest sum achievable by any contiguous subarray, using Kadane's algorithm.

Arraysintermediate
Find Minimum Subarray Sum

Finds the smallest sum achievable by any contiguous subarray.

Arraysadvanced
Find Maximum Product Subarray

Finds the largest product achievable by any contiguous subarray.

Arraysintermediate
Find Subarray With Given Sum

Finds a contiguous subarray whose elements add up to a target sum.

Arraysadvanced
Find Triplets With Given Sum

Finds three numbers in an array that add up to a target sum.

Arraysbeginner
Concatenate Arrays

Joins two arrays end to end into a single array.

Arraysintermediate
Merge Two Arrays

Merges two sorted arrays into a single sorted array.

Arraysbeginner
Move Zeros to End

Moves every zero in an array to the end, keeping the non-zero elements in order.

Arraysintermediate
Move Negative Numbers to Beginning

Rearranges an array in place so every negative number comes before the positives.

Arraysbeginner
Rotate Array Left

Rotates an array's elements to the left by a given number of positions.

Arraysbeginner
Rotate Array Right

Rotates an array's elements to the right by a given number of positions.

Arraysintermediate
Selection Sort

Sorts an array by repeatedly selecting the smallest remaining element.

Arraysintermediate
Insertion Sort

Sorts an array by inserting each element into its correct position among the ones already sorted.

Arraysintermediate
Counting Sort

Sorts small-range integers without comparisons by tallying how often each value appears.

Browse all Java programs →