Java Array

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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.