What Are Arrays in Java?

What Are Arrays in Java?

In Java, an array is a special type of variable that can hold multiple values of the same data type together.

Instead of creating many individual variables for storing similar data, we can use an array to store them all in one structured place.

Think of an array as a row of boxes, where each box can store one value, and all boxes are of the same type, like all integers, all strings, or all floats.

Each box (or element) in the array is identified by a unique index number, which starts from 0 in Java.

Simple Real-Life Example

Imagine you want to store the marks of 5 students. Without arrays, you would have to write like this:

int mark1 = 85;
int mark2 = 90;
int mark3 = 78;
int mark4 = 88;
int mark5 = 92;

That’s a lot of extra work! With an array, you can store all marks together like this:

int[] marks = {85, 90, 78, 88, 92};

Now, you have one variable, marks, that holds all 5 values. You can access them easily using their index:

  • marks[0] gives 85
  • marks[1] gives 90
  • marks[4] gives 92

Essentials Features of Java Arrays

  1. Fixed Size:
    • Once you create an array, its size cannot change. You must define how many elements it can hold when you declare it.
  2. Same Data Type:
    • All elements in an array must be of the same type, for example, all integers or all strings.
  3. Index-Based Access:
    • Every element in an array can be accessed using an index number, starting from 0.
  4. Efficient Data Management:
    • Arrays allow you to handle large amounts of data in a single variable, making your program clean and efficient.

How To Create and Access an Array in Java?

public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

System.out.println("First Element: " + numbers[0]);
System.out.println("Third Element: " + numbers[2]);
System.out.println("Fifth Element: " + numbers[4]);
}
}

Output:

First Element: 10  
Third Element: 30  
Fifth Element: 50

An array is like a container that keeps similar items together in an ordered way. It saves time, reduces code repetition, and makes it easier to perform operations such as sorting, searching, or looping through elements.

Types of Arrays in Java

In Java, arrays are mainly categorized into two types based on how they store data:

  1. Single-Dimensional Array
  2. Multi-Dimensional Array

Let’s understand both easily and practically.

1) Single-Dimensional Array Example

A single-dimensional array is the simplest form of an array. It stores data in a single line (row), just like a list of values.

You can imagine it as a single row of lockers, each with its own number (index), used to store one value.

Example of Single-Dimensional Array:

public class SingleArrayExample {
public static void main(String[] args) {
// Declare and initialize an array
int[] marks = {85, 90, 78, 92, 88};

// Display array elements using a for loop
for (int i = 0; i < marks.length; i++) {
System.out.println("Student " + (i + 1) + " scored: " + marks[i]);
}
}
}

Output:

Student 1 scored: 85  
Student 2 scored: 90
Student 3 scored: 78
Student 4 scored: 92
Student 5 scored: 88

In this code:

  • The array marks stores 5 integer values.
  • The index starts at 0 and goes up to marks.length – 1.
  • The loop accesses each element one by one using marks[i].

2) Multi-Dimensional Array Example

A multi-dimensional array is an array that contains other arrays inside it. The most common type is the two-dimensional (2D) array, which looks like a table or a matrix with rows and columns.

It’s useful for representing data like game boards, student mark sheets (rows as students, columns as subjects), grids or matrices in math problems.

Declaration

dataType[][] arrayName = new dataType[rows][columns];

Initialization

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Example of Two-Dimensional Array

public class MatrixExample {
public static void main(String[] args) {
// Declare and initialize a 2D array
int[][] matrix = {
{2, 4, 6},
{8, 10, 12},
{14, 16, 18}
};

// Display the matrix
System.out.println("Matrix Elements:");
for (int i = 0; i < matrix.length; i++) { // Loop through rows
for (int j = 0; j < matrix[i].length; j++) { // Loop through columns
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}

Output:

Matrix Elements:
2 4 6
8 10 12
14 16 18
  • The array matrix has 3 rows and 3 columns.
  • Each matrix[i] represents a row, and each matrix[i][j] represents an element inside that row.
  • Nested for loops are used to print the entire grid.

Common Array Operations

Below are some of the most commonly used operations you can perform on arrays:

1. Finding the Length of an Array

In Java, every array has a built-in property called length, which tells how many elements the array can store.

This is useful when you want to know the total number of items in the array, especially when using loops.

public class ArrayLengthExample {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
System.out.println("Total elements in array: " + numbers.length);
}
}

Output:

Total elements in array: 5

2. Updating Elements in an Array

Arrays are mutable, which means you can change their elements after initialization. You can directly access an element using its index and assign a new value to it.

For example:

public class UpdateArrayExample {
public static void main(String[] args) {
int[] scores = {40, 50, 60, 70};

System.out.println("Before update: " + scores[2]);

// Update the third element (index 2)
scores[2] = 75;

System.out.println("After update: " + scores[2]);
}
}

Output:

Before update: 60  
After update: 75
  • You can see, we changed the element at index 2 (which is the third position) from 60 to 75.

3. Copying an Array

Sometimes, you need to create a duplicate of an existing array. Instead of manually copying each element, Java provides the System.arraycopy() method to make this process faster and easier..arraycopy() method to copy arrays.

For example:

public class CopyArrayExample {
public static void main(String[] args) {
int[] original = {3, 6, 9, 12};
int[] copy = new int[original.length];

// Copy all elements from original to copy
System.arraycopy(original, 0, copy, 0, original.length);

// Display copied array
System.out.println("Copied array elements:");
for (int num : copy) {
System.out.print(num + " ");
}
}
}

Output:

Copied array elements:  
3 6 9 12

System.arraycopy(original, 0, copy, 0, original.length); means:

  • original = source array
  • 0 = start copying from index 0 in the source
  • copy = destination array
  • 0 = start pasting at index 0 in the destination
  • original.length = number of elements to copy
  • After execution, both arrays contain the same data, but they are independent in memory.

How To Use For Loop with Arrays

The enhanced for loop is also called a for-each loop. It is specifically designed to iterate over arrays or collections without needing to manually manage the index.

Syntatx:

for (dataType variable : array) {
// Code to execute for each element
}
  • variable takes the value of each element in the array one by one.
  • No need to use an index variable like i.

Example: Traversing an Array

public class EnhancedForLoopExample {
public static void main(String[] args) {
int[] scores = {15, 25, 35, 45};

// Using enhanced for loop to print each element
for (int score : scores) {
System.out.println("Score: " + score);
}
}
}

Output:

Score: 15
Score: 25
Score: 35
Score: 45

In this code:

  • The loop automatically picks each element from the scores array.
  • We don’t need to manage the index manually (like for (int i = 0; i < scores.length; i++)).

Advantages of Arrays

  1. Easy Access:
    • Arrays allow you to access any element directly using its index. This makes reading and updating values very fast and convenient.
  2. Efficient Storage:
    • All elements in an array are stored in contiguous memory locations, which reduces memory overhead and improves performance.
  3. Simplified Management:
    • Arrays group related data together under a single variable name, making it easier to organize, manage, and process multiple values efficiently.

Limitations of Arrays

  1. Fixed Size:
    • Once an array is created, its size cannot be changed. You must know the number of elements in advance or create a larger array and copy data manually.
  2. Homogeneous Data:
    • Arrays can only store elements of the same data type. You cannot mix integers, strings, or other types in a single array.
  3. No Built-In Methods:
    • Arrays do not provide advanced utility methods like collections (e.g., ArrayList), so tasks like inserting, deleting, or searching require manual coding.

Also Learn Important Topics of Java

Leave a Comment