Arrays in Java Tutorial
Chapter 09 · Java Programming Series
PBA Institute 12 min read Beginner 2024

Arrays in Java

An array stores a fixed-size collection of elements of the same type. Arrays make it possible to process many values with a single variable name. They are zero-indexed and offer constant-time access by index.

Key Features

📦

Fixed Size

Length is set at creation and cannot change.

🔢

Indexed Access

Read or write any element in O(1).

📚

Same Type

All elements must share the same data type.

🧮

for-each

Easy iteration without managing indexes.

📐

Multi-dimensional

2D, 3D arrays supported natively.

🛠️

Arrays Utility

java.util.Arrays offers sort, fill, equals and more.

Syntax

  • Declare: int arr[]; or int[] arr;
  • Create: arr = new int[5];
  • Initialize: int arr[] = {10, 20, 30};
  • Access: arr[0], length via arr.length.

Array Quick Reference

ConceptSyntaxNotesExample
Declareint arr[];No size yet
Allocatenew int[5];Default 0sarr = new int[5];
Init{1,2,3}Length 3int a[] = {1,2,3};
Lengtharr.lengthNot methodfor(i<arr.length)
SortArrays.sort(arr)Ascending

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind Arrays in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Declare & Print an Array
class Main
{
    public static void main(String args[])
    {
        int arr[] = {10, 20, 30, 40, 50};

        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
    }
}
Output 10
20
30
40
50

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Sum of Array
class Main
{
    public static void main(String args[])
    {
        int arr[] = {5, 10, 15, 20};
        int sum = 0;

        for (int x : arr)
            sum += x;

        System.out.println("Sum = " + sum);
    }
}
Output Sum = 50
Find Largest Element
class Main
{
    public static void main(String args[])
    {
        int arr[] = {12, 78, 23, 45, 67};
        int max = arr[0];

        for (int x : arr)
            if (x > max) max = x;

        System.out.println("Max = " + max);
    }
}
Output Max = 78
Sort an Array
import java.util.Arrays;

class Main
{
    public static void main(String args[])
    {
        int arr[] = {5, 1, 4, 2, 3};

        Arrays.sort(arr);

        System.out.println(Arrays.toString(arr));
    }
}
Output [1, 2, 3, 4, 5]
Reverse an Array
class Main
{
    public static void main(String args[])
    {
        int arr[] = {1, 2, 3, 4, 5};

        for (int i = arr.length - 1; i >= 0; i--)
            System.out.print(arr[i] + " ");
    }
}
Output 5 4 3 2 1
Linear Search
class Main
{
    public static void main(String args[])
    {
        int arr[] = {10, 25, 40, 55};
        int key = 40, idx = -1;

        for (int i = 0; i < arr.length; i++)
            if (arr[i] == key) { idx = i; break; }

        System.out.println("Index = " + idx);
    }
}
Output Index = 2

Notes & Tips

  • Arrays in Java are objects, not primitive types.
  • Default values are 0 / 0.0 / null / false based on type.
  • Accessing an invalid index throws ArrayIndexOutOfBoundsException.
  • Use Arrays.toString(arr) for pretty-printing.
  • Arrays have fixed length — for resizable storage use ArrayList.

Real-World Use Cases

Datasets

Store marks, temperatures, scores for batch processing.

Game Boards

2D arrays represent grids in chess, tic-tac-toe, etc.

Algorithms

Sorting and searching algorithms operate on arrays.

Buffers

Byte arrays store image/audio data in memory.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Find the minimum element of an array.
  • Q2. Count even and odd numbers in an array.
  • Q3. Find the second largest number in an array.
  • Q4. Check if an array contains a target value.
  • Q5. Compute the average of all array elements.

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 Are arrays objects in Java?
Yes — every array in Java is an object with a length field and inherits from Object.
Q2 Difference between array and ArrayList?
Arrays are fixed-size and store primitives or objects; ArrayList is resizable and stores objects only.
Q3 How are arrays stored in memory?
Elements are stored in contiguous memory for O(1) random access.
Q4 Can array size change at runtime?
No — arrays have fixed length. Use ArrayList for dynamic sizing.
Q5 What is Arrays.copyOf()?
It copies an array into a new array, optionally with a different length.

FAQ

FAQ 1 Can an array hold different types?
Not in Java — all elements must share the declared type. Use an Object[] for mixed content.
FAQ 2 Are arrays passed by reference?
The reference is passed by value, so changes to elements are visible to the caller.
FAQ 3 Why does arr.length have no parentheses?
Because length is a public final field, not a method.
FAQ 4 Can I compare arrays with ==?
No — that compares references. Use Arrays.equals() for element-wise comparison.
FAQ 5 What happens if I access arr[-1]?
ArrayIndexOutOfBoundsException is thrown at runtime.

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Arrays in Java:

  • Forgetting the semicolon ; at the end of statements while using Arrays.
  • Mixing up similar method names — read Java docs before using new APIs related to Arrays.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
String Functions 2D Arrays OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving Arrays — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
ArraysArrays conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV String Functions — strengthens your understanding of the previous building block.
NEXT 2D Arrays — the natural progression after mastering Arrays.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

Arrays store fixed-length collections of same-type elements with constant-time indexed access. Use the java.util.Arrays utility for sort, fill, copy and compare. For resizable storage, switch to ArrayList.

Continue Learning