Java – Display first element of array
class Code { public static void main(String[] args) { int[] arr = {4, 2, 8, 9, 1, 6, 7, 4}; int first = arr[0]; System.out.println(“First element is : ” + first); } } |
It is recommended to check the array contains elements or not before accessing elements:
class Code { public static void main(String[] args) { int[] arr = {4, 2, 8, 9, 1, 6, 7, 4}; if(arr.length==0) { System.out.println(“Empty array”); } else { int first = arr[0]; System.out.println(“First element is : ” + first); } } } |
We can handle ArrayIndexOutOfBoundsException instead of check the length before accessing elements:
class Code { public static void main(String[] args) { int[] arr = {4, 2, 8, 9, 1, 6, 7, 4}; try { int first = arr[0]; System.out.println(“First element is : ” + first); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(“Exception : No index to access elements”); } } } |
Java – Display first and last element of array
class Code { public static void main(String[] args) { int[] arr = {4, 2, 8, 9, 1, 6, 7, 4}; int n = arr.length; int first = arr[0]; int last = arr[n-1]; System.out.println(“First element is : ” + first); System.out.println(“Last element is : ” + last); } } |
Find the sum of first and last elements in the array
class Code { public static void main(String[] args) { int[] arr = {4, 2, 8, 9, 1, 6, 7, 5}; if(arr.length==0) { System.out.println(“Empty array”); } else { int n = arr.length; int first = arr[0]; int last = arr[n-1]; System.out.println(“Sum of First and Last elements : ” + (first+last)); } } } |