Introduction
Java Fundamentals
Java Flow Control
Object Oriented Programming
One Dimensional Arrays in Java
A one-dimensional array is the simplest form of an array in which the elements are stored linearly and can be accessed individually by specifying the index value of each element stored in the array. In this tutorial, we will learn about single-dimensional arrays with the help of examples.
Single Dimensional Arrays are arrays with one dimension. It stores the elements directly while declaring them itself.
Initialization of Single-Dimensional Arrays:
int marks[5] = { 90, 80, 85, 95, 70 };
float tamperture[] = { 20.0f, 30.2f, 40.0f, 45.2f, 30.9f };
- If an array is not initialized, it contains value depending on the storage class of the array.
- Omitting the size of the array is allowed if the array is initialized. In such cases, the compiler allocates enough space for all initialized elements.
- The values in the list are separated by commas.
- The initial values must appear in the order in which they will be assigned to the individual array elements.
- If partial Initialization is done as the one done below, all the remaining elements are initialized to zero
Example for Single-Dimensional Array:
// Java Program to demonstrate the Array example
import java.io.*;
public class Main {
public static void main(String[] args) {
int i;
int arr[] = {1, 2, 3, 4, 5};
for (i = 0; i < arr.length; i++) {
System.out.println("Array Element " + i + ": " + arr[i]);
}
}
}
Output :
Array Element 0: 1 Array Element 1: 2 Array Element 2: 3 Array Element 3: 4 Array Element 4: 5
Example of Single-Dimensional Array using for-each loop:
// Java program to demonstrate the Array example using for-each loop.
import java.io.*;
public class Main {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5};
for (int array: arr) {
System.out.println("Array Element : " + array);
}
}
}
Output :
Array Element : 1 Array Element : 2 Array Element : 3 Array Element : 4 Array Element : 5