An array is a data structure used to store multiple values in a single variable, where each value
can be accessed using an index. The elements in an array are typically of the same type (e.g.,
integers, strings).
Example:
fruits = ["apple", "banana", "cherry"]
● Here, fruits is an array (or list in java).
● It contains three elements: "apple", "banana", and "cherry".
● The first element "apple" is at index 0, "banana" is at index 1, and "cherry" is at
index 2.
Arrays are useful for organizing and managing collections of data efficiently.
Using forEach with Arrays (Streams)
In the case of arrays, you can convert them into a stream and then use forEach.
import java.util.Arrays;
public class ForEachArrayExample {
public static void main(String[] args) {
String[] animals = {"Dog", "Cat", "Elephant"};
// Using lambda expression
Arrays.stream(animals).forEach(animal -> System.out.println(animal));
// Using method reference
Arrays.stream(animals).forEach(System.out::println);
}
}
Here are examples of the different types of arrays in Java:
1. Single-Dimensional Array
A single-dimensional array is just a simple array of values.
Example (Java):
public class Main {
public static void main(String[] args) {
// Single-dimensional array
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arr[2]); // Output: 3 (Accessing the 3rd element)
2. Two-Dimensional Array
A two-dimensional array is an array of arrays, often used to represent matrices or grids.
Example (Java):
public class Main {
public static void main(String[] args) {
// Two-dimensional array (2x3 matrix)
int[][] arr = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(arr[1][2]); // Output: 6 (Accessing element in 2nd row, 3rd column)
}
3. Ragged Array
A ragged array (or jagged array) is an array of arrays where the inner arrays can have different
lengths.
Example (Java):
public class Main {
public static void main(String[] args) {
// Ragged array (rows have different lengths)
int[][] arr = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
System.out.println(arr[2][3]); // Output: 9 (Accessing 4th element of 3rd row)
4. Multi-Dimensional Array
A multi-dimensional array is an array with more than two dimensions (like 3D arrays, 4D
arrays, etc.).
Example (Java):
public class Main {
public static void main(String[] args) {
// Three-dimensional array (2x2x2)
int[][][] arr = {
{1, 2},
{3, 4}
},
{5, 6},
{7, 8}
};
System.out.println(arr[1][0][1]); // Output: 6 (Accessing element in 2nd block, 1st row, 2nd
column)
Summary:
● Single-Dimensional Array: A simple array (1D).
● Two-Dimensional Array: Array of arrays (2D).
● Ragged Array: Array of arrays with different sizes.
● Multi-Dimensional Array: Arrays with more than two dimensions (3D, 4D, etc.).
Each of these array types is useful depending on the complexity of the data and how you want
to store or manipulate it.