Learn arrays in Java from scratch with examples, indexing, loops, input, 2D arrays, ArrayList comparison, operations, complexity, and DSA tips.
Arrays in Java: A Complete Beginner's Guide
Suppose you need to store the marks of 100 students. You could create 100 separate variables, but that would quickly become difficult to write, read, and manage. Instead, Java gives you arrays, which allow you to store multiple values of the same data type under a single variable name.
Arrays are one of the first data structures every Java beginner should understand. They are simple to use, but they also form the foundation for many important DSA concepts such as searching, sorting, two pointers, sliding window, prefix sums, binary search, and dynamic programming.
What Is an Array in Java?
An array in Java is a fixed-size collection of elements of the same data type, stored under a single variable name and accessed using an index.
For example:
int[] marks = {85, 90, 78, 92, 88};
This array stores five integer values. Instead of creating five separate variables, we store all the marks inside one array called marks.
The important characteristics of Java arrays are:
- Same data type: An integer array stores integers, a double array stores doubles, and so on.
- Fixed size: Once an array is created, its size cannot be changed directly.
- Index-based access: Each element is accessed using its index.
- Zero-based indexing: The first element is at index
0, not1.
For the array above:
Index: 0 1 2 3 4
Value: 85 90 78 92 88
So, marks[0] is 85, while marks[4] is 88.
Why Are Arrays Used in Java?
Arrays are useful whenever you need to work with multiple related values. Instead of creating many individual variables, you can organize the values inside one structure.
Common reasons to use arrays include:
- Storing multiple values of the same type.
- Keeping related data organized.
- Accessing elements quickly using an index.
- Working efficiently with collections of primitive values.
- Performing searching and sorting operations.
- Building a strong foundation for learning DSA.
For example, arrays are frequently used for student marks, temperatures, product prices, employee IDs, scores, and many other types of data.
More importantly for students, many DSA problems begin with an array. If you are preparing for coding interviews, being comfortable with arrays is essential.
How to Declare an Array in Java
To declare an array, you specify the data type followed by square brackets.
int[] numbers;
This tells Java that numbers will refer to an integer array. However, no array has been created yet.
Java also allows this syntax:
int numbers[];
Both forms are valid. However, int[] numbers is generally preferred because it makes it clearer that the variable is an array type.
How to Create an Array in Java
After declaring an array, you can create it using the new keyword.
int[] numbers = new int[5];
The expression new int[5] creates an array capable of storing five integers.
Because Java arrays use zero-based indexing, the valid indexes are:
0, 1, 2, 3, 4
When an array is created without explicitly providing values, Java assigns default values to its elements.
int→0double→0.0boolean→false- Reference types →
null
For example:
int[] numbers = new int[5];
System.out.println(numbers[0]);
The output is:
0
How to Initialize an Array in Java
There are several common ways to declare and initialize Java arrays.
Method 1: Declare and Initialize Separately
int[] numbers;
numbers = new int[5];
This approach is useful when you want to declare the variable first and create the array later.
Method 2: Declare and Initialize Together
int[] numbers = new int[5];
This is a common approach when you know the required size but do not yet have the values.
Method 3: Initialize With Values
int[] numbers = {10, 20, 30, 40, 50};
This is convenient when you already know the elements. Java automatically determines the size from the number of values provided.
Here, the array contains five elements, so its length is 5.
Understanding Array Indexing
One of the most important things to understand about an array in Java is indexing.
Java arrays use zero-based indexing. That means the first element is stored at index 0.
int[] numbers = {10, 20, 30, 40, 50};
The indexes work like this:
numbers[0] → 10
numbers[1] → 20
numbers[2] → 30
numbers[3] → 40
numbers[4] → 50
Notice that the first index is 0, not 1.
Because the array has five elements, the last valid index is 4.
Therefore:
numbers[5]
is invalid and will cause an ArrayIndexOutOfBoundsException.
Easy rule to remember: For an array of length
n, valid indexes are from0ton - 1.
How to Access Array Elements
You can access an array element by writing the array name followed by the index inside square brackets.
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]);
System.out.println(numbers[2]);
System.out.println(numbers[4]);
Output:
10
30
50
Here:
numbers[0]accesses the first element.numbers[2]accesses the third element.numbers[4]accesses the last element.
How to Modify Array Elements
Arrays are mutable, which means you can change the value stored at an existing index.
int[] numbers = {10, 20, 30, 40, 50};
numbers[2] = 100;
System.out.println(numbers[2]);
Output:
100
Before modification, the array was:
{10, 20, 30, 40, 50}
After numbers[2] = 100, it becomes:
{10, 20, 100, 40, 50}
Only the value at index 2 was replaced.
How to Find the Length of an Array
You can find the number of elements in a Java array using the length property.
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers.length);
Output:
5
Remember that length is a property, not a method. Therefore, you write:
numbers.length
and not:
numbers.length()
It is also important not to confuse the following:
array.length→ length of an array.String.length()→ method that returns the length of a String.ArrayList.size()→ method that returns the number of elements in an ArrayList.
How to Traverse an Array
Traversal means visiting each element of an array, usually one by one.
Using a Standard for Loop
The traditional for loop is one of the most important ways to work with arrays, especially in DSA.
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Output:
10
20
30
40
50
Let's understand the loop:
int i = 0starts at the first index.i < numbers.lengthensures we stay within the valid indexes.i++moves to the next index.numbers[i]accesses the current element.
Notice that we use < rather than <=. Using <= would eventually try to access an invalid index.
Using the Enhanced for Loop
Java also provides an enhanced for loop, often called a for-each loop.
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number);
}
This is convenient when you simply want to read every element and do not need the index.
Use the standard for loop when you need the index or want more control over traversal. Use the enhanced for loop when you simply want to visit every element.
Taking Array Input From the User in Java
A common beginner exercise is taking an array from the user. The Scanner class can be used for this.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter array size: ");
int n = scanner.nextInt();
int[] numbers = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println("Array elements:");
for (int number : numbers) {
System.out.println(number);
}
scanner.close();
}
}
Here is what the program does:
- Creates a
Scannerobject. - Asks the user for the array size.
- Creates an integer array using that size.
- Uses a loop to read each element.
- Stores each value at the appropriate index.
- Uses another loop to print the elements.
- Closes the scanner when input is complete.
For example, if the user enters:
5
10 20 30 40 50
The program stores those five values in the array.
Common Operations on Arrays
Once you understand how arrays work, you can perform many common operations on them.
- Traversal: Visit every element.
- Searching: Find whether a particular value exists.
- Updating: Change an element at a specific index.
- Finding maximum: Find the largest value.
- Finding minimum: Find the smallest value.
- Finding sum: Add all elements.
- Counting: Count elements that satisfy a condition.
- Reversing: Change the order of elements.
- Sorting: Arrange elements in increasing or decreasing order.
Finding the Sum
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("Sum = " + sum);
The loop visits every element and adds it to sum.
Finding the Maximum
int[] numbers = {10, 45, 23, 67, 12};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum = " + max);
We initially assume the first element is the maximum. Then we compare the remaining elements with it.
Finding the Minimum
int[] numbers = {10, 45, 23, 67, 12};
int min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
System.out.println("Minimum = " + min);
Reversing an Array
One common DSA exercise is reversing an array.
int[] numbers = {10, 20, 30, 40, 50};
int left = 0;
int right = numbers.length - 1;
while (left < right) {
int temp = numbers[left];
numbers[left] = numbers[right];
numbers[right] = temp;
left++;
right--;
}
for (int number : numbers) {
System.out.print(number + " ");
}
The idea is simple: swap the first and last elements, then move toward the middle.
Searching in an Array
Searching means finding whether a particular value exists in an array and, often, finding its index.
Linear Search
Linear search is the simplest searching technique. Start from the first element and compare each value with the target.
int[] numbers = {10, 25, 30, 45, 50};
int target = 30;
int index = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
index = i;
break;
}
}
System.out.println("Index = " + index);
The algorithm works like this:
- Start from the first element.
- Compare it with the target.
- If it matches, stop.
- If it does not match, move to the next element.
- Continue until the target is found or the array ends.
Linear search works even when the array is not sorted.
Binary Search
Binary search is a faster searching technique for suitable search spaces, especially sorted arrays. Instead of checking every element one by one, it repeatedly divides the search range in half.
For example, if you are searching for a value in a sorted array, you can check the middle element. Depending on whether the target is smaller or larger, you can eliminate half of the remaining search space.
Binary search is an important DSA topic because its time complexity is typically O(log n) on a sorted array with random access. If you have already started learning Binary Search Explained Simply, arrays are the perfect place to practice it.
Sorting an Array in Java
Sorting means arranging array elements in a particular order, such as ascending or descending order.
Java provides the Arrays.sort() method for sorting arrays.
import java.util.Arrays;
int[] numbers = {50, 20, 40, 10, 30};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
Output:
[10, 20, 30, 40, 50]
Built-in sorting is useful in real Java programs, but if you are preparing for DSA interviews, do not stop at Arrays.sort(). You should also understand how common sorting algorithms work.
Important sorting algorithms include:
- Bubble Sort
- Selection Sort
- Insertion Sort
- Merge Sort
- Quick Sort
You do not need to master all of them while learning the basics of arrays. Learn them separately as you progress through DSA.
Multidimensional Arrays in Java
A one-dimensional array stores values in a single sequence. A multidimensional array allows you to organize data across multiple dimensions.
The most common example is a two-dimensional array, or 2D array. You can think of it like a table with rows and columns.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
This matrix has three rows and three columns.
You can visualize it like this:
1 2 3
4 5 6
7 8 9
The first index represents the row, and the second index represents the column.
matrix[0][0] → 1
matrix[1][2] → 6
matrix[2][1] → 8
For example, matrix[1][2] means row 1, column 2.
Traversing a 2D Array
To visit every element in a 2D array, you can use nested loops.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
The outer loop moves through the rows, while the inner loop moves through the columns of each row.
Jagged Arrays in Java
Java also supports arrays where different rows can have different lengths. These are commonly called jagged arrays.
int[][] numbers = {
{1, 2},
{3, 4, 5},
{6}
};
Here:
- The first row contains 2 elements.
- The second row contains 3 elements.
- The third row contains 1 element.
This is different from a traditional rectangular matrix where every row has the same number of columns.
Java supports this because a 2D array is essentially an array whose elements are themselves arrays.
Arrays of Objects in Java
Arrays are not limited to primitive values such as int, double, and boolean. They can also store references to objects.
For example, suppose you have a Student class:
class Student {
String name;
Student(String name) {
this.name = name;
}
}
You can create an array of Student objects:
Student[] students = new Student[3];
students[0] = new Student("Rahul");
students[1] = new Student("Priya");
students[2] = new Student("Aman");
The array stores references to Student objects. This is different from an int[], which directly stores integer values.
One important point for beginners is that an object array created with new Student[3] initially contains null references. You need to create and assign the individual objects before using them.
Array vs ArrayList in Java
Beginners often wonder whether they should use an array or an ArrayList. Both are useful, but they are designed for different situations.
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Primitive types | Yes | Uses wrapper classes such as Integer |
| Syntax | Simple | More collection-oriented |
| Performance | Generally efficient with low overhead | Has some collection and boxing overhead |
| Resizing | Not directly supported | Automatically grows as needed |
| Methods | Limited built-in operations | Many useful methods |
| Best use | Fixed-size data and many DSA problems | Dynamic collections |
For example, an array is a natural choice when you know you need exactly 10 elements:
int[] numbers = new int[10];
An ArrayList is more convenient when the number of elements may change:
import java.util.ArrayList;
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
For DSA practice, arrays are extremely important even if real-world Java applications often use collection classes such as ArrayList.
Common Array Exceptions and Mistakes
ArrayIndexOutOfBoundsException
This exception occurs when you try to access an index that does not exist.
int[] numbers = new int[5];
System.out.println(numbers[5]);
The valid indexes are 0 through 4, so index 5 is invalid.
Using Index 1 for the First Element
A common beginner mistake is assuming the first element is at index 1.
int[] numbers = {10, 20, 30};
System.out.println(numbers[0]);
The first element is always at index 0.
Using <= Instead of <
This is a very common DSA mistake.
Incorrect:
for (int i = 0; i <= numbers.length; i++) {
System.out.println(numbers[i]);
}
Correct:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
When i becomes equal to numbers.length, the index is already outside the valid range.
Forgetting That Array Size Is Fixed
If you create:
int[] numbers = new int[5];
you cannot simply add a sixth element using numbers[5]. You would need a different array or a dynamic collection such as ArrayList.
Confusing length With size()
Use:
numbers.length
for an array.
Use:
list.size()
for an ArrayList.
Modifying the Wrong Index
Always remember that the index identifies the position, not the value itself.
int[] numbers = {10, 20, 30};
numbers[1] = 100;
This changes 20, because 20 is at index 1.
Forgetting to Initialize an Array
Declaring an array does not create it.
int[] numbers;
You cannot use numbers[0] until the variable refers to an actual array.
You need something like:
numbers = new int[5];
Using Null References With Object Arrays
When you create:
Student[] students = new Student[3];
the elements initially contain null. You must assign actual Student objects before accessing their fields or methods.
Array Time Complexity
Understanding time complexity is important when learning DSA. It helps you estimate how an operation behaves as the size of the input grows.
| Operation | Typical Time Complexity |
|---|---|
| Access by index | O(1) |
| Update by index | O(1) |
| Linear search | O(n) |
| Traversal | O(n) |
| Insert at a known unused position | O(1) |
| Insert while shifting elements | O(n) |
| Delete while shifting elements | O(n) |
Why is accessing an element by index O(1)? Arrays provide direct indexed access. Given an index, the runtime can calculate where that element is located without scanning all previous elements.
However, insertion and deletion need more context. A fixed array does not automatically resize. If elements must be shifted to make space or close a gap, the operation can take O(n) time.
For example, inserting an element near the beginning may require many existing elements to move one position.
Why Arrays Are Important for DSA
Arrays are one of the most important foundations of DSA. Many problems that appear complicated at first become easier once you are comfortable with indexes, loops, and array manipulation.
Arrays connect directly to many later topics, including:
- Strings: Strings can be processed using character positions and array-like indexing concepts.
- Two pointers: Two indexes move through an array to solve problems efficiently.
- Sliding window: A moving range is maintained over an array or string.
- Prefix sums: Additional arrays can store cumulative information.
- Hashing: Arrays are closely related to how hash tables and frequency structures work internally.
- Binary search: Sorted arrays provide an ideal setting for binary search.
- Sorting: Many sorting algorithms operate directly on arrays.
- Matrices: 2D arrays are used for grid and matrix problems.
- Recursion: Many recursive problems use arrays as input.
- Dynamic programming: Arrays are frequently used to store previously calculated results.
This is why you should not rush through arrays just because the syntax looks simple. Strong array fundamentals make later DSA topics much easier to understand.
Beginner Array Problems to Practice
Do not jump directly into difficult interview problems. Build your skills gradually.
Level 1 — Basic
- Print all elements of an array.
- Find the sum of all elements.
- Find the maximum element.
- Find the minimum element.
- Count even and odd numbers.
- Search for an element.
Level 2 — Intermediate
- Reverse an array.
- Find the second largest element.
- Remove duplicates.
- Move zeroes to the end.
- Rotate an array.
- Merge two arrays.
Level 3 — DSA Patterns
- Two Sum.
- Maximum subarray.
- Two pointers.
- Sliding window.
- Prefix sum.
- Binary search.
The goal is not to memorize solutions. Try to understand the technique behind each problem. Once you understand the pattern, you can apply the same idea to many different questions.
How to Practice Arrays Effectively
If you are completely new to DSA, follow a simple progression instead of solving random problems.
- Understand indexing: Be comfortable with indexes from
0tolength - 1. - Write basic programs: Create arrays, print elements, and modify values.
- Practice traversal: Become comfortable with standard and enhanced loops.
- Solve searching problems: Start with linear search before binary search.
- Practice manipulation: Reverse, rotate, swap, and rearrange elements.
- Learn sorting: Understand basic sorting algorithms and their complexities.
- Learn common patterns: Study two pointers, sliding window, prefix sums, and related techniques.
- Solve DSA problems: Gradually move from easy to medium-level problems.
- Analyze complexity: Ask yourself how much time and space your solution uses.
- Revisit difficult problems: Keep track of problems you struggled with and solve them again later without looking at the solution.
Most importantly, try to write the code yourself before checking an explanation. Getting stuck is part of learning DSA.
Common Mistakes Beginners Make While Learning Arrays
1. Starting DSA Without Understanding Indexing
If you are confused about indexes, array problems will become unnecessarily difficult. Practice simple examples until zero-based indexing feels natural.
2. Using Incorrect Loop Boundaries
Remember that the last valid index is length - 1. In most array traversals, the condition should be i < array.length.
3. Confusing Index and Value
In numbers[2] = 50, 2 is the index and 50 is the value. Keeping this distinction clear is essential.
4. Ignoring Edge Cases
Do not test your solution only with large arrays. Also think about an empty array, a single-element array, duplicate values, negative numbers, and already sorted data.
5. Assuming Arrays Can Grow Automatically
Java arrays have a fixed length. If you need a collection that can grow, consider an ArrayList.
6. Memorizing Code Instead of Understanding It
Copying a solution may help you finish one problem, but understanding why it works will help you solve the next ten.
7. Ignoring Time Complexity
Two solutions can produce the same answer while having very different performance. Get into the habit of asking whether your solution is O(n), O(n log n), or something else.
8. Jumping Into Advanced Problems Too Early
Master basic traversal, searching, and manipulation before attempting complicated array patterns.
9. Not Practicing Enough
Reading an array tutorial is not the same as knowing arrays. Write programs and solve problems regularly until the operations become natural.
Frequently Asked Questions
What is an array in Java?
An array is a fixed-size collection of elements of the same data type. Each element can be accessed using its index, starting from index 0.
Are Java arrays fixed in size?
Yes. Once a Java array is created, its length cannot be changed directly. If you need a dynamically growing collection, ArrayList is often more suitable.
Why does Java use zero-based indexing?
Zero-based indexing is a common convention in programming. It also works naturally with how indexed memory locations are calculated, making direct element access efficient.
How do I find the length of an array?
Use the length property:
int length = numbers.length;
Do not write numbers.length() for an array.
What is the difference between an array and ArrayList?
An array has a fixed length, while an ArrayList can grow or shrink dynamically. Arrays are especially important for DSA, while ArrayList is useful when you need a flexible collection.
Can an array store different data types?
A primitive array such as int[] stores only integers. An object array stores references to objects of its declared type, although Java's inheritance rules can allow compatible subtype objects to be stored in certain reference-type arrays.
What is a 2D array in Java?
A 2D array is an array of arrays commonly used to represent tables, matrices, grids, and other two-dimensional data.
How do I take array input in Java?
You can use the Scanner class to read the array size and then use a loop to read each element.
Are arrays important for DSA?
Yes. Arrays are one of the most important foundations of DSA. Searching, sorting, two pointers, sliding window, prefix sums, binary search, matrices, and many other concepts build on array fundamentals.
How long does it take to learn arrays in Java?
The basic syntax can be learned in a day, but becoming comfortable with array-based DSA problems takes practice. Focus on understanding the concepts and solving progressively harder problems rather than trying to finish in a fixed number of days.
Final Takeaway
Arrays may look simple, but they are one of the most important building blocks in Java and DSA. You should be comfortable declaring an array, creating it, initializing values, accessing elements using indexes, modifying values, finding its length, traversing it with loops, taking input, searching, sorting, and working with 2D arrays.
Once these basics become comfortable, start solving small array problems and gradually learn patterns such as two pointers, sliding window, prefix sums, and binary search.
If you are preparing for Java interviews or starting DSA from zero, do not underestimate arrays. A strong understanding of Java arrays will make many of the topics you learn later much easier.
Comments
Post a Comment
If you have any suggestions then comment me .