In Java, an array is a data structure that allows you to store multiple values of the same data type in a single variable. Arrays are essential for working with collections of data, and they provide a way to group elements under a single name. Here's an overview of how arrays work in Java:
There are two types of array.
1.Single Dimensional Array
2.Multidimensional Array
1.Single Dimensional Array:-A single-dimensional array in Java is a basic type of array that stores elements of the same data type in a linear sequence. It is sometimes referred to as a one-dimensional array. You declare and work with single-dimensional arrays using square brackets []. Here's how you can create and use a single-dimensional array in Java:
Declaring a Single-Dimensional Array: To declare a single-dimensional array, you specify the data type of the elements it will hold, followed by square brackets [], and provide a name for the array variable.
For example:
dataType [] arr;
dataType[] arr;
dataType arr[];
dataType[] arrayName; // Example: int[] numbers;
Creating a Single-Dimensional Array: After declaring a single-dimensional array, you need to create it by specifying its size (i.e., the number of elements it can hold). You can create an array using the new keyword.
For example:
int[] numbers = new int[5]; // Creates an array of 5 integers
This creates an array that can hold five int values, and it initializes them with default values (which is 0 for numeric types).
Initializing a Single-Dimensional Array: You can also initialize a single-dimensional array with values when you create it:
int[] numbers = {1, 2, 3, 4, 5}; // Initializes an array with values
Accessing Elements of a Single-Dimensional Array: Array elements are accessed using zero-based indexing, meaning the first element is at index 0, the second element at index 1, and so on. You can access elements using square brackets []:
int firstNumber = numbers[0]; // Access the first element
int secondNumber = numbers[1]; // Access the second element
Array Length: You can determine the length (number of elements) of a single-dimensional array using the length property:
int arrayLength = numbers.length; // Gives the length of the array (5 in this case)
Iterating through a Single-Dimensional Array: You can use loops, such as for or foreach, to iterate through the elements of a single-dimensional array:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Enhanced for loop (foreach loop)
for (int num : numbers) {
System.out.println(num);
}
Single-dimensional arrays are commonly used in Java to store and manipulate collections of data when you only need one level of organization. They are fundamental in many programming tasks and are essential for organizing and processing data efficiently.
class Demo{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output:
10
20
70
40
50
In Java, a multidimensional array is an array of arrays, which means you can have arrays nested within other arrays. Commonly used multidimensional arrays include 2D arrays and 3D arrays, but you can create arrays with even more dimensions if needed. Here's how to work with multidimensional arrays in Java:
A 2D array is an array of arrays. It's like having an array where each element is another array. In Java, 2D arrays are typically used to represent tables, grids, or matrices.
Declaration and Initialization:
To declare and initialize a 2D array, you specify two sets of square brackets [][]
dataType[][] arrayName = new dataType[rows][columns];
int[][] matrix1;
int [][] matrix2;
int matrix3[][];
int[] matrix4[];
For example:
int[][] matrix = new int[3][4]; // 3 rows and 4 columns
You can also initialize a 2D array with values:
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Example:-
public class TwoDArrayExample {
public static void main(String[] args) {
int[][] matrix = new int[3][3]; // A 3x3 matrix
// Initializing elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
matrix[i][j] = i + j;
}
}
// Accessing elements
System.out.println(matrix[1][1]); // Output: 2
}
}
Output
2
In this example, we first declare a 2D array called matrix with dimensions 3x3. Then, we use nested loops to initialize each element of the array. Finally, we access and print an element.
public class MatrixExample {
public static void main(String[] args) {
// Declare and initialize a 2D array (matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements in the matrix
int element = matrix[1][2]; // Accesses the element in the second row and third column (value 6)
System.out.println("Element at matrix[1][2]: " + element);
// Iterate through the matrix and print its elements
System.out.println("Matrix elements:");
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println(); // Move to the next row
}
}
}
In this example:
We declare and initialize a 2D array matrix with three rows and three columns.
We access a specific element in the matrix (element at matrix[1][2], which is 6) and print it.
We use nested for loops to iterate through the matrix and print all its elements row by row.
When you run this program, it will display the following output:
Element at matrix[1][2]: 6
Matrix elements:
1 2 3
4 5 6
7 8 9
3D Arrays java
In Java, a 3D array is an array of 2D arrays. It extends the concept of a 2D array into three dimensions.
Here's an example of a 3D array in Java, including how to declare, initialize, access elements, and iterate through it:
public class ThreeDArrayExample {
public static void main(String[] args) {
// Declare and initialize a 3D array
int[][][] threeDArray = {
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
},
{
{10, 11, 12},
{13, 14, 15},
{16, 17, 18}
}
}; // Accessing elements in the 3D array
int element = threeDArray[1][0][2]; // Accesses an element in the second "layer," first row, third column (value 12)
System.out.println("Element at threeDArray[1][0][2]: " + element);
// Iterate through the 3D array and print its elements
System.out.println("3D Array elements:");
for (int layer = 0; layer < threeDArray.length; layer++) {
System.out.println("Layer " + layer + ":");
for (int row = 0; row < threeDArray[layer].length; row++) {
for (int col = 0; col < threeDArray[layer][row].length; col++) {
System.out.print(threeDArray[layer][row][col] + " ");
}
System.out.println(); // Move to the next row within the layer
}
}
}
}
in this example:
We declare and initialize a 3D array threeDArray with two "layers," each containing a 3x3 matrix.
We access a specific element in the 3D array (element at threeDArray[1][0][2], which is 12) and print it.
We use nested for loops to iterate through the 3D array, layer by layer, row by row, and column by column, and print all its elements.
When you run this program, it will display the following output:
Element at threeDArray[1][0][2]: 12
3D Array elements:
Layer 0:
1 2 3
4 5 6
7 8 9
Layer 1:
10 11 12
13 14 15
16 17 18
This demonstrates the basic operations of working with a 3D array in Java. You can extend this concept to higher-dimensional arrays as needed for your specific application.
Using a one-dimensional array and find the average of numbers.
public class Average {
public static void main(String[] args) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = calculateAverage(nums);
System.out.println("Average is " + result);
}
public static double calculateAverage(double[] arr) {
if (arr.length == 0) {
return 0.0; // Handle the case of an empty array
}
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
} return sum / arr.length;
}
}
Output
Average is 12.299999999999999
The following program numbers each element in the array from left to right, top to bottom, and then displays these values