Contents

Arrays

Arrays in Java

Operators are the foundation of any programming language, enabling us to perform various computations, logic evaluations, and functions. Java offers several types of operators that are categorized based on the functions they perform.

Array Initialization in C

Initialization in C involves assigning initial values to variables. When an array is declared or memory is allocated for it, its elements initially contain garbage values. To give these elements meaningful values, we initialize the array. There are several methods for initializing an array in C.

1. Array Initialization During Declaration :This method involves initializing the array at the time of its declaration. We use an initializer list, which is a set of values enclosed in curly braces { } and separated by commas, to assign values to the array.

Examples:

				
					int[] numbers; // Declaring an integer array

				
			

This declares an integer array numbers. However, it does not allocate memory yet.

2. Creating an Array :Allocate memory using the new keyword:

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

				
			

This initializes the array to hold 5 integers, with default values of 0.

3. Accessing Array Elements :You can access and modify array elements using their index (starting from 0):

				
					numbers[0] = 10; // Setting the first element to 10
int firstElement = numbers[0]; // Accessing the first element

				
			

4. Changing Array Elements :To update an element, assign a new value:

				
					numbers[0] = 20; // Changes the first element to 20

				
			

5. Array Length :You can get the length of an array using its length property:

				
					int length = numbers.length; // Returns 5 for this array

				
			

6. Array Initialization :You can declare and initialize arrays in different ways:

				
					int[] numbers = new int[5]; // Declaration + memory allocation
int[] otherNumbers = {1, 2, 3, 4, 5}; // Array literal initialization

				
			

7. Iterating Through Arrays :You can loop through arrays using a for loop or for-each loop:

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

for (int number : numbers) {
    System.out.println(number); // For-each loop
}

				
			

8. Multidimensional Arrays :Java supports multidimensional arrays, like 2D arrays (matrix):

				
					int[][] matrix = new int[3][3]; // 2D array
matrix[0][0] = 1;

				
			

Example:

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

				
			

9. Array of Objects ;Arrays can also hold objects of a class:

				
					Student[] students = new Student[3]; // Array of Student objects
students[0] = new Student("John", 1);

				
			

Output:

				
					num1 = 20
num2 = 10
The product = 200

				
			

10. Passing Arrays to Methods :You can pass arrays to methods:

				
					public class MultiplicationExample {
    public static void main(String[] args) {
        int num1 = 20, num2 = 10;
        int product = num1 * num2;
        System.out.println("The product = " + product);
    }
}

				
			

Calling the method:

				
					printArray(numbers);
				
			

11. Returning Arrays from Methods :A method can return an array:

				
					public static int[] getArray() {
    return new int[] {1, 2, 3};
}

				
			

12. Cloning Arrays :To clone an array (create a shallow copy):

				
					int[] cloneArray = numbers.clone();

				
			

For multidimensional arrays, the cloning creates a shallow copy, meaning only the references are copied, not the actual elements.

13. Handling Array Exceptions :If you try to access an element outside the array size, Java throws an ArrayIndexOutOfBoundsException:

				
					System.out.println(numbers[5]); // Throws an exception if the array has fewer elements

				
			

Arrays class in Java

The Arrays class in Java, part of the java.util package, provides several static methods to help developers perform operations on arrays in a more optimized and efficient manner. Here are some of the most common methods:

Key Methods in Arrays Class:

1. asList(): Converts an array to a fixed-size list.

				
					Integer[] arr = {1, 2, 3};
List<Integer> list = Arrays.asList(arr);

				
			

2. binarySearch(): Searches for a specific element using the binary search algorithm.

				
					int[] arr = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(arr, 3); // Returns index of 3

				
			

3. compare()Compares two arrays lexicographically.

				
					int result = Arrays.compare(arr1, arr2);
				
			

4. copyOf(): Copies the array to a new array of a specified length.

				
					int[] newArr = Arrays.copyOf(arr, 10); // Extends or truncates

				
			

5. copyOfRange(): Copies a range of an array.

				
					int[] newArr = Arrays.copyOfRange(arr, 1, 3);

				
			

6. deepEquals():Compares two arrays deeply for nested arrays.

				
					boolean isEqual = Arrays.deepEquals(arr1, arr2);

				
			

7. deepHashCode(): Returns the hash code based on the “deep contents” of an array.

				
					int hashCode = Arrays.deepHashCode(arr);
				
			

8. deepToString(): Converts an array to a string representation, handling nested arrays.

				
					String arrStr = Arrays.deepToString(arr);
				
			

9. equals(): Compares two arrays for equality.

				
					boolean isEqual = Arrays.equals(arr1, arr2);
				
			

10. fill(): Fills an array with a specified value.

				
					Arrays.fill(arr, 100); // Fills all elements with 100
				
			

11. hashCode(): Returns the hash code for an array.

				
					int hash = Arrays.hashCode(arr);
				
			

12. mismatch(): Finds the first index where two arrays differ.

				
					int mismatchIndex = Arrays.mismatch(arr1, arr2);

				
			

13. parallelSort(): Sorts the array in parallel for faster sorting.

				
					Arrays.parallelSort(arr);

				
			

14. sort(): Sorts an array in ascending order.

				
					Arrays.sort(arr);

				
			

15. spliterator(): Returns a Spliterator covering the array.

				
					Spliterator<Integer> spliterator = Arrays.spliterator(arr);

				
			

16. stream(): Converts an array into a sequential stream.

				
					Stream<int[]> stream = Arrays.stream(arr);

				
			

17. toString(): Converts an array to a string representation.

				
					String arrStr = Arrays.toString(arr);

				
			
Multidimensional Arrays

Multidimensional arrays, simply put, are arrays made up of arrays. Data within these arrays are stored in a tabular structure, typically in row-major order.

Syntax:

				
					data_type[1st_dimension][2nd_dimension][]...[Nth_dimension] array_name = new data_type[size1][size2]...[sizeN];

				
			

Where:

  • data_type: The type of data stored in the array (e.g., int, char, etc.).
  • dimension: Specifies the dimension of the array (e.g., 2D, 3D).
  • array_name: The name assigned to the array.
  • size1, size2,…, sizeN: Dimensions defining the size of the array.

Examples:

Two-dimensional array:

				
					int[][] twoD_arr = new int[10][20];

				
			

The total number of elements a multidimensional array can store is the product of its dimensions. For example, an array int[][] x = new int[10][20] can hold a total of 10×20=20010 \times 20 = 200 elements. Similarly, int[][][] x = new int[5][10][20] can store 5×10×20=10005 \times 10 \times 20 = 1000 elements.

Applications of Multidimensional Arrays
  • Tabular Data: These arrays are often used to store tabular data, such as a student’s roll number and marks. A more complex use is to store images in 3D arrays.
  • Dynamic Programming: Many dynamic programming problems leverage multidimensional arrays to store intermediate states.
  • Algorithms: Common applications include matrix multiplication, adjacency matrices in graphs, and grid-based search problems.
Two-Dimensional Array (2D Array)

A 2D array is the most basic form of a multidimensional array and can be viewed as an array of one-dimensional arrays.

Declaration (Indirect Method):

Example:

				
					int[][] arr = new int[10][20];

				
			

Initialization:

				
					arr[0][0] = 1;

				
			

Examples:

				
					public class TwoDArrayExample {
    public static void main(String[] args) {
        int[][] arr = new int[10][20];
        arr[0][0] = 1;

        System.out.println("arr[0][0] = " + arr[0][0]);
    }
}

				
			

Output:

				
					arr[0][0] = 1

				
			

Example: 2D array with default values in a 4×4 matrix:

				
					public class TwoDArray {
    public static void main(String[] args) {
        int rows = 4;
        int columns = 4;
        int[][] array = new int[rows][columns];

        int value = 1;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                array[i][j] = value++;
            }
        }

        System.out.println("The 2D array is:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }
}

				
			

Output:

				
					The 2D array is: 
1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16

				
			

Declaration (Direct Method):

				
					int[][] arr = {{1, 2}, {3, 4}};

				
			

Output:

				
					After adding: 8

				
			

Example:

				
					public class DirectTwoDArray {
    public static void main(String[] args) {
        int[][] arr = { { 1, 2 }, { 3, 4 } };

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

				
			

Output:

				
					arr[0][0] = 1
arr[0][1] = 2
arr[1][0] = 3
arr[1][1] = 4

				
			

Accessing Elements:

To access elements in a 2D array, the syntax is:

				
					array[row_index][column_index];

				
			

For example:

				
					arr[0][0] = 1;

				
			
Three-Dimensional Array (3D Array)

A 3D array can be seen as an array of 2D arrays.

Declaration (Indirect Method):

				
					int[][][] arr = new int[10][20][30];

				
			

Initialization:

				
					arr[0][0][0] = 1;
				
			

Different Ways To Declare And Initialize 2-D Array

A multi-dimensional array is an array with more than one dimension, commonly used as 2D or 3D arrays. Essentially, a multi-dimensional array is an array of arrays. A typical example of a 2D array is a chessboard, which consists of a grid of 64 square boxes arranged in 8 rows and 8 columns. Similarly, a 2D array can be visualized as a grid, where each element is identified by a row and column number. Accessing elements in a 2D array is similar to working with an Excel sheet, using row and column indices.

Two-dimensional arrays (2D arrays) are useful for implementing structures like games (Tic-Tac-Toe, Chess) or storing image pixels.

Declaring a 2D Array in Java

A 2D array can be declared in two common ways:

				
					data_type array_name[][];   // OR
data_type[][] array_name;

				
			
  • data_type: This defines the type of elements the array will store, such as int, String, boolean, etc. Java, being statically typed, requires the data type to be declared.
  • array_name: This is the name you assign to the array.

Example: Declaring Different Types of 2D Arrays

				
					data_type[][] array_Name = new data_type[no_of_rows][no_of_columns];

				
			

Here, no_of_rows and no_of_columns define the number of rows and columns in the array. The total number of elements in a 2D array is calculated by multiplying the number of rows by the number of columns. For instance:

				
					int[][] myArray = new int[4][5];  // A 2D array with 4 rows and 5 columns

				
			

By default, Java assigns default values to the array elements depending on the data type. Below are various approaches to initialize a 2D array.

Different Approaches for Initializing 2D Arrays

Approach 1: Declaration and Initialization

In this approach, we declare the array and immediately initialize it.

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

				
			

Example:

				
					public class Example {
    public static void main(String[] args) {
        int[][] integer2DArray = new int[3][4];
        System.out.println("Default value of int array element: " + integer2DArray[0][0]);  // Outputs 0

        String[][] string2DArray = new String[2][3];
        System.out.println("Default value of String array element: " + string2DArray[0][0]);  // Outputs null

        boolean[][] boolean2DArray = new boolean[2][2];
        System.out.println("Default value of boolean array element: " + boolean2DArray[0][0]);  // Outputs false
    }
}

				
			

Approach 2: Initialization with Values

Here, we initialize the array elements directly without specifying the number of rows and columns. Java automatically deduces the size.

Example:

				
					public class Example {
    public static void main(String[] args) {
        String[][] courses = {
            { "Math", "Science", "History" },       // Row 1
            { "Biology", "Physics", "Chemistry" },  // Row 2
            { "English", "Art" }                    // Row 3
        };

        System.out.println("Course in first row: " + courses[0][0]);  // Math
        System.out.println("Course in second row: " + courses[1][2]);  // Chemistry
        System.out.println("Course in third row: " + courses[2][1]);  // Art
    }
}

				
			

Approach 3: Initializing Each Element Separately

This method allows you to initialize elements individually.

Example:

				
					public class Example {
    public static void main(String[] args) {
        int[][] marks = new int[2][2];
        marks[0][0] = 85;
        marks[0][1] = 90;
        marks[1][0] = 78;
        marks[1][1] = 88;

        System.out.println("marks[0][0] = " + marks[0][0]);
        System.out.println("marks[1][1] = " + marks[1][1]);
    }
}

				
			

Approach 4: Using Loops for Initialization

When dealing with large arrays, initializing elements manually can be cumbersome. A more efficient approach is using loops.

Example:

				
					public class Example {
    public static void main(String[] args) {
        int rows = 4, columns = 3;
        int[][] array = new int[rows][columns];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                array[i][j] = i + j;
            }
        }

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

				
			

Approach 5: Jagged Arrays (Different Number of Columns per Row)

A jagged array allows rows to have different numbers of columns.

Example:

				
					public class Example {
    public static void main(String[] args) {
        int[][] jaggedArray = new int[2][];
        jaggedArray[0] = new int[3];  // First row has 3 columns
        jaggedArray[1] = new int[2];  // Second row has 2 columns

        jaggedArray[0][0] = 1;
        jaggedArray[0][1] = 2;
        jaggedArray[0][2] = 3;
        jaggedArray[1][0] = 4;
        jaggedArray[1][1] = 5;

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

				
			

Jagged Arrays in Java

A jagged array is a type of multidimensional array where the number of columns varies from row to row. This makes the jagged array more flexible compared to a rectangular 2D array. Here’s a simplified representation of a jagged array in memory:

				
					Row 1: [ ]  
Row 2: [   ]  
Row 3: [         ]
...

				
			

Declaring and Initializing a Jagged Array

Syntax:

				
					data_type array_name[][] = new data_type[n][];
array_name[0] = new data_type[n1];  // n1 = no. of columns in row-1
array_name[1] = new data_type[n2];  // n2 = no. of columns in row-2
...

				
			

Alternative Ways to Initialize a Jagged Array:

				
					int[][] arr = new int[][] {
    new int[] {10, 20, 30, 40},
    new int[] {50, 60, 70, 80, 90, 100},
    new int[] {110, 120}
};

				
			

or simply:

				
					int[][] arr = {
    {10, 20, 30, 40},
    {50, 60, 70, 80, 90, 100},
    {110, 120}
};

				
			

Example 1: Jagged Array with Uneven Rows

				
					public class Main {
    public static void main(String[] args) {
        // Declare a 2D array with 2 rows
        int[][] jaggedArray = new int[2][];

        // First row has 3 columns
        jaggedArray[0] = new int[3];
        
        // Second row has 2 columns
        jaggedArray[1] = new int[2];

        // Initializing the array
        int value = 0;
        for (int i = 0; i < jaggedArray.length; i++) {
            for (int j = 0; j < jaggedArray[i].length; j++) {
                jaggedArray[i][j] = value++;
            }
        }

        // Displaying the values of the jagged array
        System.out.println("Contents of the Jagged Array:");
        for (int i = 0; i < jaggedArray.length; i++) {
            for (int j = 0; j < jaggedArray[i].length; j++) {
                System.out.print(jaggedArray[i][j] + " ");
            }
            System.out.println();
        }
    }
}

				
			

Output:

				
					Contents of the Jagged Array:
0 1 2
3 4

				
			

Example 2: Creating a Jagged Array with Incremental Row Sizes

In this example, the first row contains one element, the second row contains two elements, and so on.

				
					public class Main {
    public static void main(String[] args) {
        int rows = 5;

        // Declaring a jagged array with 5 rows
        int[][] jaggedArray = new int[rows][];

        // Creating the jagged array with varying columns per row
        for (int i = 0; i < jaggedArray.length; i++) {
            jaggedArray[i] = new int[i + 1];  // ith row has i+1 columns
        }

        // Initializing the array
        int value = 0;
        for (int i = 0; i < jaggedArray.length; i++) {
            for (int j = 0; j < jaggedArray[i].length; j++) {
                jaggedArray[i][j] = value++;
            }
        }

        // Displaying the values of the jagged array
        System.out.println("Contents of the Jagged Array:");
        for (int i = 0; i < jaggedArray.length; i++) {
            for (int j = 0; j < jaggedArray[i].length; j++) {
                System.out.print(jaggedArray[i][j] + " ");
            }
            System.out.println();
        }
    }
}

				
			

Output:

				
					Contents of the Jagged Array:
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14

				
			

Final Arrays

In Java, the final keyword prevents reassigning a reference to another object, but it doesn’t make the referenced object itself immutable. This is applicable to arrays as well. Once an array is declared as final, the reference to that array cannot be changed, but the elements within the array can be modified. This means we can change the state of the object (the contents of the array), but not the reference to the object itself.

Illustration:

				
					// Java Program Demonstrating Final Arrays

public class FinalArrayDemo {
    public static void main(String[] args) {
        final int[] arr = { 1, 2, 3, 4, 5 };

        // Modifying an element in the final array
        arr[3] = 10;

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

				
			

Output:

				
					1
2
3
10
5

				
			

Implementation: Here’s another example showing how you can manipulate the contents of a final array:

				
					// Java Program Demonstrating Final Arrays

public class FinalArrayExample {
    public static void main(String[] args) {
        final int[] arr = { 2, 4, 6, 8, 10 };

        // Modifying array elements
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 2;
            System.out.println(arr[i]);
        }
    }
}

				
			

Output:

				
					4
8
12
16
20

				
			

Explanation:

Even though the array arr is declared as final, you can still change its individual elements. The final keyword simply means that the reference to the array cannot be reassigned to another array. This behavior is consistent with how object references work in Java: when you declare an object as final, the reference can’t be changed, but the object’s internal state can still be modified.

Example 1:

				
					// Program demonstrating modification of object fields

class Test {
    int value = 100;

    public static void main(String[] args) {
        final Test obj = new Test();
        obj.value = 200;  // Modifying the internal state
        System.out.println(obj.value);
    }
}

				
			

Output:

				
					200

				
			

util.Arrays vs reflect.Array in Java with Examples

The Array class in the java.lang.reflect package is part of Java Reflection and provides static methods to dynamically create and access Java arrays. This class is final, meaning it cannot be instantiated or extended. All its methods are static and accessed via the class name itself. On the other hand, the Arrays class in the java.util package is part of the Java Collection Framework and contains various utility methods for manipulating arrays, such as sorting and searching.

While both classes deal with arrays, the key difference is their usage. The Array class ensures type safety and is mainly used for reflective access to arrays. The Arrays class, on the other hand, offers a variety of methods for array operations.

Here is a breakdown of the differences between Array and Arrays:

FactorArrayArrays
PackageBelongs to java.lang.reflectBelongs to java.util
Class Hierarchyjava.lang.Objectjava.lang.reflect.Arrayjava.lang.Objectjava.util.Arrays
ImmutabilityImmutable and finalNot immutable
Declarationpublic final class Array extends Objectpublic class Arrays extends Object
UsageProvides methods to create and access arrays reflectively, ensuring type safetyContains utility methods for array manipulation (sorting, searching, etc.)

Example: Illustrating the Usage of Array vs Arrays

				
					import java.lang.reflect.Array;
import java.util.Arrays;

public class ArrayVsArraysExample {

    public static void main(String[] args) {

        // Creating an integer array of size 5
        int[] intArray = new int[5];

        // Adding an element to the array using Array class
        Array.setInt(intArray, 0, 42);

        // Printing the array using Arrays class
        System.out.println(Arrays.toString(intArray));
    }
}

				
			

Output:

				
					[42, 0, 0, 0, 0]