среда, 3 января 2024 г.

Arrays in Java

    An array is a data structure that allows you to store multiple values of the same data type under a single variable name. Each element in the array is accessed by its index, starting from 0. Arrays in Java are fixed in size, meaning their length cannot be changed after creation.

  • Declaration and Initialization:

//Single-Dimensional Array:
// Declaration and initialization of an integer array
int[] numbers = new int[5]; // Creates an array of size 5

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

//Multi-Dimensional Array:
// Declaration and initialization of a 2D array
int[][] matrix = new int[3][4]; // Creates a 3x4 matrix

// Initializing a 2D array with values
int[][] identityMatrix = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};

  • Accessing Array Elements:

// Accessing and modifying elements in a single-dimensional array
numbers[0] = 10;
int secondNumber = numbers[1];

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

  • Iterating Through an Array:

// Using a for loop to iterate through a single-dimensional array
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

// Using nested loops to iterate through a 2D array
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}


// Using enhanced for loop to iterate through a single-dimensional array
for (int num : numbers) {
System.out.println(num);
}

// Using enhanced for loop to iterate through a 2D array
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}


Arrays are fundamental in Java programming and are used in various scenarios to store and manipulate collections of data. Keep in mind that arrays have a fixed size, and if dynamic resizing is needed, other data structures like ArrayList may be more suitable.

Комментариев нет:

Отправить комментарий