Advertisement

Google Ad Slot: content-top

Java Array

~1 min read · Java
On this page

An array in Java is a container object that holds a fixed number of elements of the same type. It is a data structure used to store multiple values in a single variable, making it easier to manage collections of data.

Types of Arrays

  1. One-Dimensional Array: A list of elements in a single row.
  2. Multi-Dimensional Array: Arrays with multiple rows and columns (e.g., 2D arrays).


One-Dimensional Array:

Syntax:

dataType[] arrayName = newdataType[size];
Example
// Declare and initialize an array int[] numbers = new int[5]; // Array with 5 elements // Assign values to the array numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; // Access and print elements System.out.println("First element: " + numbers[0]); System.out.println("Third element: " + numbers[2]); // Loop through the array System.out.println("Array elements:"); for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
Try it yourself

Multi-Dimensional Array:

Syntax:

dataType[][] arrayName = new dataType[rows][columns];


Example
// Declare and initialize a 2D array int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Access and print elements System.out.println("Element at (0, 1): " + matrix[0][1]); // 2 System.out.println("Element at (2, 2): " + matrix[2][2]); // 9 // Loop through the 2D array System.out.println("Matrix:"); 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(); }
Try it yourself

Enhanced For Loop (For-Each Loop):

The for-each loop is used to iterate over arrays or collections without using an index. It's simpler and avoids potential errors with index handling.

Example
int[] numbers = {10, 20, 30, 40}; for (int num : numbers) { System.out.println(num); }
Try it yourself