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
| Concept | Syntax | Notes | Example |
|---|---|---|---|
| Declare | int arr[]; | No size yet | |
| Allocate | new int[5]; | Default 0s | arr = new int[5]; |
| Init | {1,2,3} | Length 3 | int a[] = {1,2,3}; |
| Length | arr.length | Not method | for(i<arr.length) |
| Sort | Arrays.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.
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]);
}
}
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.
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);
}
}
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);
}
}
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));
}
}
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] + " ");
}
}
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);
}
}
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.
Yes — every array in Java is an object with a
length field and inherits from Object.
Arrays are fixed-size and store primitives or objects; ArrayList is resizable and stores objects only.
Elements are stored in contiguous memory for O(1) random access.
No — arrays have fixed length. Use ArrayList for dynamic sizing.
Arrays.copyOf()?It copies an array into a new array, optionally with a different length.
FAQ
Not in Java — all elements must share the declared type. Use an Object[] for mixed content.
The reference is passed by value, so changes to elements are visible to the caller.
arr.length have no parentheses?Because
length is a public final field, not a method.
No — that compares references. Use
Arrays.equals() for element-wise comparison.
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
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
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| Arrays | Arrays concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
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.