How to Get First Element in Array in Java?
Last Updated : 24 Dec, 2024
Improve
In Java, to get the first element in an array, we can access the element at index 0 using array indexing.
Example 1: Below is a simple example that demonstrates how to access the element at index 0
in an array.
public class Geeks {
public static void main(String[] args) {
// Declare and initialize an array
int[] n = {5, 15, 25, 35, 45};
// Access the first element
int f = n[0];
// Print the first element
System.out.println("" + f);
}
}
Output
5
Syntax
arrayName[0];
- arrayName: The name of the array.
- [0]: The index of the first element in the array.
Example 2: Here, we are trying to access the first element in an empty array. It will throw an ArrayIndexOutOfBoundsException.
// Handling empty arrays
public class Geeks {
public static void main(String[] args) {
// Declare an empty array
int[] n = {};
// Check if the array is empty
if (n.length > 0) {
System.out.println("The first element is: " + n[0]);
} else {
System.out.println("The array is empty.");
}
}
}
Output
The array is empty.
Example 3: Here, we are accessing the first element in an Array of String.
// Access the first element
// in a String array
public class Geeks {
public static void main(String[] args) {
// Declare and initialize a string array
String[] s = {"Cherry", "Strawberry", "Blueberry"};
// Access the first element
String f = s[0];
// Print the first element
System.out.println(" " + f);
}
}
Output
Cherry