java get first element of array code example

Example 1: get last element of array java

firstNum = numbers[0];
lastNum = numbers[numbers.length-1];

Example 2: java last element in array

arrayName[arrayName.length() - 1];

Example 3: how to get the last element of array in java

int[] arr = new int[5]; //length of the array is 5
int val = arr[arr.length - 1]; //here variable val stores the last element of arr

Example 4: java list get first element

list.get(0);

Example 5: java get first element from arraylist

import java.util.ArrayList;
public class FirstandLastElemets{
   public static void main(String[] args){
      ArrayList<String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the Array List: \n"+list);
      //Removing the sub list
      System.out.println("First element of the array list: "+list.get(0));
      System.out.println("Last element of the array list: "+list.get(list.size()-1));
   }
}