;
Java Basics July 21 ,2025

Arrays in Java – A Complete Guide for Students

1. Introduction to Arrays

An array in Java is a collection of variables of the same type. Instead of declaring individual variables like int a, b, c, you can declare an array int[] arr = new int[3]; that can store multiple values.

Arrays store elements in contiguous memory locations and are accessed using an index, starting from 0.

Arrays in Java are objects, and memory for them is allocated at runtime using the new keyword.

int[] numbers = new int[5]; // creates an array of 5 integers

2. Why Use Arrays?

  • Efficient way to store multiple values under a single variable name
  • Saves memory and improves code readability
  • Ideal for performing operations like searching, sorting, filtering
  • Easily iterable using loops
  • Enhances modular programming and data structure use

Here is a detailed explanation of One-Dimensional Arrays in Java, covering each point from declaration to finding the array length:

3. One-Dimensional Arrays – 

A one-dimensional array in Java is a linear structure that holds elements of the same data type in contiguous memory locations. It is ideal when you want to store a fixed number of items like marks of students, daily temperatures, etc.

a. Declaration

To declare a one-dimensional array, use either of the following syntaxes:

int[] arr;  // Preferred modern style
int arr[];  // Also valid (from C/C++ style)

Both are correct, but the first style is more commonly used in Java because it clearly indicates that arr is an array of integers.

At this point, the array reference is declared but not initialized — meaning it doesn’t point to any actual memory space yet.

b. Initialization

You can initialize the array in two ways:

  1. Using the new keyword:
arr = new int[5];

This creates an array of size 5 and initializes all elements to 0 (default value for int).

  1. Declare and initialize in one line:
int[] arr = {10, 20, 30, 40};

This is called array literal initialization, and it sets the values directly during declaration.

c. Accessing Elements

You can access elements using their index, which starts from 0.

System.out.println(arr[0]);  // Prints the first element
System.out.println(arr[3]);  // Prints the fourth element

Accessing an index that doesn’t exist (e.g., arr[5] if size is 4) will throw an ArrayIndexOutOfBoundsException.

d. Modifying Elements

To change the value of a specific element, assign a new value using its index:

arr[2] = 100;

This replaces the third element of the array with 100. Arrays are mutable — meaning you can change values anytime after creation.

e. Traversing Arrays

Traversing an array means accessing each element of the array one by one. This is usually done using loops such as the traditional for loop or the enhanced for-each loop. . You can use:

1. Traditional for loop:

This loop gives access to each element using an index, which is useful when you need to:

  • Access elements in reverse
  • Compare elements at specific positions
  • Modify elements directly by index

 

for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

Here, you manually control the index, which is useful when you need to manipulate indices (like reversing or comparing).

2. Enhanced for-each loop:

This loop simplifies reading each element without using an index. It’s useful for:

  • Iterating through all elements when modification or index tracking is not needed
for (int num : arr) {
    System.out.println(num);
}

This loop automatically fetches each element without needing an index. It’s clean and ideal for reading values, but doesn’t allow changing elements directly.

f. Finding Array Length

Finding the length of an array means determining how many elements are stored in it. In Java, this is done using the built-in .length property of arrays.

  • It returns the number of elements in the array.
  • It helps avoid runtime errors like accessing elements beyond the array's size.
int len = arr.length;
System.out.println("Length of array: " + len);

Remember:

  • .length is a property (not a method — so no parentheses).
  • It helps prevent errors like accessing out-of-bound indexes.

 

4. Multidimensional Arrays

A multidimensional array in Java is an array containing other arrays as its elements. It can have two or more dimensions, allowing you to represent data in tabular or matrix form. The most common type is the 2D array, used to represent rows and columns like a table.

a. 2D Arrays (Matrix)

A 2D array is an array of arrays, often visualized as a matrix with rows and columns.
It is declared as:

int[][] matrix = new int[3][4]; // 3 rows and 4 columns

This creates a table-like structure:

[
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0]
]

All values are initialized to 0 (default for int). You can also declare and initialize in a single step:

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

Each inner array represents a row.

b. Accessing and Modifying Elements

You can access or update elements in a 2D array using two indices:

System.out.println(matrix[1][2]); // prints 6
matrix[1][2] = 99;               // sets value at 2nd row, 3rd column to 99
  • The first index refers to the row.
  • The second index refers to the column.

c. Traversing a 2D Array

Traversing a 2D array means accessing all its elements using nested loops:

for (int i = 0; i < matrix.length; i++) { // rows
    for (int j = 0; j < matrix[i].length; j++) { // columns
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

Explanation:

  • matrix.length gives the number of rows.
  • matrix[i].length gives the number of columns in row i.

d. Jagged Arrays (Irregular 2D Arrays)

A jagged array is a special type of 2D array where rows have different lengths (i.e., number of columns can vary per row).

int[][] jagged = new int[3][];
jagged[0] = new int[2];   // Row 0 has 2 columns
jagged[1] = new int[4];   // Row 1 has 4 columns
jagged[2] = new int[1];   // Row 2 has 1 column

You can fill values like this:

jagged[0][0] = 10;
jagged[1][3] = 25;

Each row is initialized separately, and can have different lengths.

Traversal also uses nested loops, adapting to each row’s length:

for (int i = 0; i < jagged.length; i++) {
    for (int j = 0; j < jagged[i].length; j++) {
        System.out.print(jagged[i][j] + " ");
    }
    System.out.println();
}

e. Advantages of Multidimensional Arrays

  • Best suited for tabular data (e.g., matrices, grids).
  • Helps represent real-world scenarios (marks of students, game boards).
  • Supports multiple levels of nested structures.

5. Array Operations 

Java arrays are of fixed size. That means once an array is created, you cannot resize it directly. To perform operations like inserting or deleting, you must create a new array or use helper logic to simulate dynamic behavior.

a. Inserting Elements into an Array

❖ Problem:

You want to insert a new element into an existing array.

Since Java arrays are fixed in size, you must create a new array with a larger size and copy all existing elements along with the new one.

❖ Example:

int[] original = {1, 2, 3};
int[] newArray = new int[4]; // new size is original + 1

// Copy existing elements
for (int i = 0; i < original.length; i++) {
    newArray[i] = original[i];
}

// Insert new element at the end
newArray[3] = 4;

// Output new array
for (int val : newArray) {
    System.out.print(val + " ");
}

❖ Output:

1 2 3 4

❖ Note:

If you want to insert the element in the middle, shift elements from the insertion index forward.

b. Deleting Elements from an Array

❖ Problem:

You want to remove an element at a specific index.

Since arrays are fixed-size, you cannot "remove" an element but can shift elements left to overwrite the deleted value.

❖ Example:

int[] arr = {10, 20, 30, 40, 50};
int deleteIndex = 2; // remove 30

for (int i = deleteIndex; i < arr.length - 1; i++) {
    arr[i] = arr[i + 1]; // shift elements left
}

arr[arr.length - 1] = 0; // optional: mark last as empty

for (int val : arr) {
    System.out.print(val + " ");
}

❖ Output:

10 20 40 50 0

❖ Note:

You still have a fixed-size array. To actually shrink it, you'd need to create a smaller array.

c. Merging Two Arrays

❖ Problem:

You want to combine two arrays into one.

You’ll need to create a new array with the combined size and then copy all elements from both arrays.

❖ Example:

int[] a = {1, 2, 3};
int[] b = {4, 5};
int[] result = new int[a.length + b.length];

// Copy first array
for (int i = 0; i < a.length; i++) {
    result[i] = a[i];
}

// Copy second array
for (int i = 0; i < b.length; i++) {
    result[a.length + i] = b[i];
}

for (int val : result) {
    System.out.print(val + " ");
}

❖ Output:

1 2 3 4 5

Summary

OperationPossible Directly?Requires New Array?Involves Shifting?
InsertNoYesYes (if not appending)
DeleteNoOptionalYes
MergeNoYesNo (just copy both)

 

 

6. ArrayList (Dynamic Arrays)

In Java, an ArrayList is a part of the java.util package and provides a way to create dynamic arrays — arrays that can grow and shrink in size at runtime. This makes ArrayList a powerful alternative to fixed-size arrays.

a. Importing ArrayList

To use ArrayList, you must first import it:

import java.util.ArrayList;

b. Creating an ArrayList

ArrayList list = new ArrayList<>();

Here:

  • ArrayList<> is the class.
  • Integer is the data type (generics are used because primitive types like int can't be directly used).
  • The list is initially empty.

c. Adding Elements

Use the .add() method to insert elements:

list.add(10);
list.add(20);
list.add(30);

This will result in: [10, 20, 30]

You can also add at a specific index:

list.add(1, 15); // Inserts 15 at index 1

Now the list becomes: [10, 15, 20, 30]

d. Removing Elements

Use .remove(index) to remove by index:

list.remove(0); // Removes the first element (10)

List now becomes: [15, 20, 30]

You can also remove by value:

list.remove(Integer.valueOf(20)); // Removes 20 by value

List becomes: [15, 30]

e. Displaying the List

You can simply print the entire list:

System.out.println(list);

This prints: [15, 30]

f. Traversing an ArrayList

1. Using for-each loop:

for (int item : list) {
    System.out.println(item);
}

2. Using traditional for loop:

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

g. Common Methods in ArrayList

MethodDescription
add(value)Adds element to the end
add(index, value)Inserts element at specified index
remove(index)Removes element at given index
remove(Object)Removes first occurrence of the object
get(index)Returns the element at specified index
set(index, value)Replaces element at given index
size()Returns number of elements
clear()Removes all elements
contains(value)Checks if value is present

h. Example: Complete Code

import java.util.ArrayList;

public class ArrayListDemo {
    public static void main(String[] args) {
        ArrayList list = new ArrayList<>();

        list.add(10);
        list.add(20);
        list.add(30);
        list.remove(0); // removes 10

        System.out.println("List after removal: " + list);

        for (int num : list) {
            System.out.println(num);
        }
    }
}

Output:

List after removal: [20, 30]
20
30

i. Advantages of ArrayList over Arrays

FeatureArrayArrayList
SizeFixedDynamic
Data TypesCan be primitiveOnly Objects (use wrappers)
FlexibilityLimitedHigh (built-in methods)
Insert/DeleteManual code requiredBuilt-in methods available
PerformanceFasterSlightly slower

 

7. Common Array Algorithms – 

These are basic algorithms used for solving common problems with arrays in Java.

a. Linear Search –

Linear Search is a simple method to find a specific value (called a key) in an array.
It checks each element one by one from start to end.

for (int i = 0; i < arr.length; i++) {
    if (arr[i] == key) {
        return i;  // index where the key is found
    }
}
  • If the key is found, it returns the index.
  • If not found, it usually returns -1 (though not shown in your snippet).
  • Time Complexity: O(n) – slower for large arrays.

b. Binary Search – 

Binary Search is a faster method but works only on sorted arrays.
It repeatedly divides the search range in half until the key is found.

int low = 0, high = arr.length - 1;
while (low <= high) {
    int mid = (low + high) / 2;
    if (arr[mid] == key) return mid;
    else if (arr[mid] < key) low = mid + 1;
    else high = mid - 1;
}
  • Starts with the full array (low to high)
  • Finds the mid index and compares the value with key
  • Narrows the range based on the comparison
  • Returns index of the key if found
  • Time Complexity: O(log n) – much faster than linear search

c. Reverse an Array –

Reversing an array means swapping the first element with the last, second with second-last, and so on.

for (int i = 0; i < arr.length / 2; i++) {
    int temp = arr[i];
    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = temp;
}
  • The loop runs only halfway through the array
  • It uses a temporary variable temp to swap values
  • This reverses the array in-place, meaning no extra array is used

d. Count Frequency –

Counting frequency means finding how many times a particular value (target) appears in the array.

int count = 0;
for (int i = 0; i < arr.length; i++) {
    if (arr[i] == target) count++;
}
  • Starts with a count of 0
  • Increments count every time the target value is found
  • Returns the total number of occurrences

Let me know if you want a summary table or real-world examples for each!
 

8. Edge Cases & Exceptions

  • Accessing out-of-bound index throws ArrayIndexOutOfBoundsException
  • Arrays are fixed in size
  • Uninitialized array elements hold default values
  • Null arrays can throw NullPointerException

9. Array vs ArrayList – Comparison

FeatureArrayArrayList
SizeFixedDynamic
Type SupportPrimitives + ObjObjects only
PerformanceFasterSlightly slower
FlexibilityLessMore methods (add, remove, etc.)

 Conclusion

Arrays in Java are essential for organizing and processing data efficiently. They offer fast access using indexes, can be used with loops for powerful manipulation, and serve as the foundation for advanced data structures. Understanding both static arrays and dynamic ArrayLists prepares students for real-world programming and algorithm challenges.

Next Blog- Method in Java

Sanjiv
0

You must logged in to post comments.

Get In Touch

123 Street, New York, USA

+012 345 67890

techiefreak87@gmail.com

© Design & Developed by HW Infotech