Arrays in Java
Subject: Data Structures and Algorithms · Language: Java · Level: beginner · 6 min read
Learn Java arrays, indexing, traversal, input, maximum, minimum, sum, and common DSA patterns.
An array is a data structure that stores multiple values of the same data type in a single variable. For example, if you want to store marks of 50 students, creating 50 separate variables is not practical. An array lets you store all marks under one name and access each value using an index.
Arrays are one of the most important topics in Java DSA because many problems are based on indexing, traversal, searching, sorting, prefix sum, two pointers, and sliding window. If a student becomes comfortable with arrays, many later DSA topics become easier to understand.
Why Arrays Are Needed
Arrays help us manage a group of related values in an organized way. Instead of writing `mark1`, `mark2`, `mark3`, and so on, we can write one array named `marks` and store all values inside it. This makes the program shorter, easier to read, and easier to process using loops. Once values are stored in an array, the same loop can calculate sum, find maximum, count elements, or search for a target.
Declaring and Creating an Array
In Java, an array must be declared with a data type. The size is fixed when the array is created.
```java
int[] arr = new int[5];
```
This creates an integer array that can store 5 integer values. `int[]` means the array stores integers. `arr` is the array name. `new int[5]` creates space for 5 integers.
You can also declare an array with values directly.
```java
int[] numbers = {10, 20, 30, 40, 50};
```
Array Indexing
Java arrays use zero-based indexing. The first element is at index `0`, and the last element is at index `n - 1`. For example, if an array has 5 elements, valid indexes are `0`, `1`, `2`, `3`, and `4`.
```java
int[] arr = {10, 20, 30, 40, 50};
System.out.println(arr[0]);
System.out.println(arr[4]);
```
`arr[0]` prints the first value, which is 10. `arr[4]` prints the last value, which is 50. If you access an invalid index, Java throws `ArrayIndexOutOfBoundsException`. This means the program tried to access a position that does not exist.
Array Length
Java arrays have a built-in `length` property. It tells how many elements the array can store.
```java
int[] arr = {5, 10, 15};
System.out.println(arr.length);
```
Here, `arr.length` gives 3. Remember: `length` is a property for arrays, not a method. So write `arr.length`, not `arr.length()`.
Default Values in Arrays
When an array is created using `new`, Java automatically fills it with default values.
- `int`, `long`, `byte`, and `short` arrays get 0
- `float` and `double` arrays get 0.0
- `char` arrays get the null character
- `boolean` arrays get false
- object arrays such as `String[]` get null
This is different from C, where uninitialized local arrays may contain garbage values.
Taking Array Input
To take array input from the user, first read the size, create the array, and then use a loop to read each element.
```java
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
``` The loop starts from 0 because array indexing starts from 0. It runs while `i < n` because the last valid index is `n - 1`.
Traversing an Array
Traversal means visiting each element one by one. Most array problems use a loop from `0` to `n - 1`.
```java
for (int i = 0; i < n; i++) {
System.out.println(arr[i]);
}
```
Traversal is used when we need to print elements, calculate sum, count values, find maximum, find minimum, search for a target, or update array values.
Updating Array Elements
Array values can be changed using their index.
```java
int[] arr = {10, 20, 30};
arr[1] = 99;
```
After this, the array becomes `{10, 99, 30}` because index 1 was updated.
Common Array Operations
Most beginner array problems are based on simple operations.
- Sum: add all elements of the array
- Maximum: find the largest value
- Minimum: find the smallest value
- Count: count values that satisfy a condition
- Search: check whether a target value exists
- Reverse: print or store elements in opposite order
- Sort: arrange values in increasing or decreasing order
Common Array Patterns
In DSA, arrays are not only about storing values. They are used to build problem-solving patterns.
- Prefix sum is used when repeated range sum queries are required
- Two pointers are used when we process an array from two sides
- Sliding window is used for subarray problems
- Frequency arrays are used for counting values or characters
- Sorting helps in searching, duplicate handling, and pair-based problems
One-Dimensional Array
A one-dimensional array stores values in a single line-like structure.
```java
int[] marks = {80, 75, 90, 88};
```
This type of array is commonly used for lists of numbers, marks, prices, scores, and DSA input arrays.
Two-Dimensional Array
A two-dimensional array stores data in rows and columns. It is useful for matrices, grids, tables, and board-based problems.
```java
int[][] matrix = new int[3][3];
```
Here, `matrix` has 3 rows and 3 columns. To access an element, we use two indexes: one for row and one for column.
```java
matrix[0][1] = 25;
```
Array Program: Sum, Maximum, and Minimum
This program takes array elements from the user and prints the sum, maximum value, and minimum value.
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n]; System.out.print("Enter " + n + " elements: ");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
} int sum = 0;
int max = arr[0];
int min = arr[0];
for (int i = 0; i < n; i++) {
sum += arr[i];
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
} System.out.println("Sum = " + sum);
System.out.println("Maximum = " + max);
System.out.println("Minimum = " + min);
}
}
```
Arrays and Memory
In Java, arrays are objects. When we create an array using `new`, memory is allocated for that array. The array variable stores a reference to the array object. This means when an array is passed to a method, the method can change the original array values.
Important Points to Remember
- Array size is fixed after creation
- Array indexing starts from 0
- Last valid index is `length - 1`
- Arrays store values of the same data type
- Accessing an invalid index causes `ArrayIndexOutOfBoundsException`
- Arrays are very important for DSA and interview preparation
Practice Question
Take `n` numbers as input and print how many numbers are even and how many are odd.