Understanding Java Arrays for DSA

In Java, arrays are a fundamental data structure that stores a fixed-size sequential collection of elements of the same type.

Declaration

dataType[] arrayName;

Example:

int[] numbers;

Initialization

Arrays can be initialized in several ways:

  1. Using the new Keyword

     int[] numbers = new int[5]; // Creates an array of 5 zeros
    
  2. Directly with values

     int[] numbers = {1, 2, 3, 4, 5};
    
  3. Combining declaration and initialization

     int[] numbers = new int[]{1, 2, 3, 4, 5};
    

Accessing Elements

Elements of an array are accessed using their index. The index starts from 0.

int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Outputs: 1

Array Length

The length of an array can be obtained using the length property.

int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers.length); // Outputs: 5

Multidimensional Arrays

Java supports multidimensional arrays, which are arrays of arrays.

  1. Declaration

     int[][] matrix = new int[3][3];
    
  2. Initialization

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

Array Methods

Java provides several utility methods for arrays in the java.util.Arrays class.

  1. Sorting

     int[] numbers = {5, 3, 4, 1, 2};
     Arrays.sort(numbers);
    
  2. Searching

     int[] numbers = {1, 2, 3, 4, 5};
     int index = Arrays.binarySearch(numbers, 3);
    
  3. Filling

     int[] numbers = new int[5];
     Arrays.fill(numbers, 10);
    
  4. Copying

     int[] numbers = {1, 2, 3, 4, 5};
     int[] copy = Arrays.copyOf(numbers, numbers.length);
    

Array Limitations

  1. Fixed Size: Once an array is created, its size cannot be changed.

  2. Homogeneous: All elements in an array must be of the same type.

Array of Objects

Arrays can also hold objects.

String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";

Enhanced for Loop

Java provides an enhanced for loop to iterate over arrays.

int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    System.out.println(number);
}

Thank you for reading!

You can support me by buying me a book.