Arrays

In Java, arrays are used to store collections of elements of the same data type. Arrays have a fixed size, which means you must specify the size when you declare an array, and you cannot change the size after it's created. Here are some common operations with arrays and examples:

Declaring and Initializing Arrays:

// Declaring an array of integers
int[] numbers;

// Initializing an array with values
int[] primes = {2, 3, 5, 7, 11};

// Initializing an array with a specified size
int[] scores = new int[5];
scores[0] = 95;
scores[1] = 88;
scores[2] = 72;
scores[3] = 90;
scores[4] = 85;

Accessing Array Elements:

// Accessing elements by index
int firstPrime = primes[0]; // firstPrime will be 2

// Modifying elements by index
primes[1] = 13; // Changes the second element to 13

Array Length:

You can find the length of an array using the length property.

int[] numbers = {1, 2, 3, 4, 5};
int length = numbers.length; // length will be 5

Iterating Through an Array:

You can use loops to iterate through the elements of an array.

int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

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

Multidimensional Arrays:

Java supports multidimensional arrays, including 2D arrays.

// Declaring and initializing a 2D array
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Accessing elements in a 2D array
int element = matrix[1][2]; // element will be 6

Array Copy:

You can copy one array into another using System.arraycopy or by manually iterating through the elements.

int[] sourceArray = {1, 2, 3};
int[] destinationArray = new int[sourceArray.length];

System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);

// Using a loop to copy
for (int i = 0; i < sourceArray.length; i++) {
    destinationArray[i] = sourceArray[i];
}

Array Sorting:

You can sort arrays using the Arrays.sort method for arrays of primitive types or by implementing the Comparable interface for custom objects.

int[] numbers = {5, 2, 8, 1, 3};
Arrays.sort(numbers); // Sorts the array in ascending order

String[] names = {"Alice", "Bob", "Eve", "Charlie"};
Arrays.sort(names); // Sorts the array in alphabetical order

These are some common operations with arrays in Java. Arrays are a fundamental data structure in Java and are widely used in various programming scenarios.

Last updated