A single dimensional array in Java is a collection of elements of the same data type stored in a continuous memory location. Each element is accessed using an index starting from 0.
0 and ends at length - 1Java provides multiple ways to declare and initialize a single dimensional array.
// Declaration of an integer array
int[] numbers;
// Allocation of memory for 5 integers
numbers = new int[5];
// Program to demonstrate single dimensional array
public class Main {
public static void main(String[] args) {
// Creating and initializing the array
int[] marks = {85, 90, 78, 92, 88};
// Accessing array elements using loop
for(int i = 0; i < marks.length; i++) {
System.out.println("Marks: " + marks[i]);
}
}
}
Marks: 85
Marks: 90
Marks: 78
Marks: 92
Marks: 88
Each value is printed by accessing the array using its index inside a loop.
array.length instead of hardcoded values