To remove the first element from the array using Java, we can create a new array of size one less than the original array.
Now we will copy the all element starting from array index 1 from original array to new array.
The second logic we can do like shifting one element towards the left, which will remove the first element from the array.
Program 1: Remove the first element from the array java
- In this program to remove the first element from an array, we have created a new array.
- Now copy all the array elements to the new array starting index from 1.
- By doing this the element that is at index 0 will be not copied to a new array.
- Now print the new array to get the desired output.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Java Program to delete First element from Array");
System.out.print("Enter the size of array: ");
int size = sc.nextInt();
int arr[] = new int[size];
for(int i=0; i<size; i++) {
System.out.print("Please give value for index "+ i +" : ");
arr[i] = sc.nextInt();
}
int newArr[] = new int[arr.length - 1];
for (int i = 1; i < arr.length; i++) {
newArr[i-1] = arr[i];
}
System.out.println("New Array After Removing First Element: ");
System.out.println(Arrays.toString(newArr));
}
}
Output
Java Program to delete First element from Array
Enter the size of array: 5
Please give value for index 0 : 1
Please give value for index 1 : 2
Please give value for index 2 : 3
Please give value for index 3 : 4
Please give value for index 4 : 5
New Array After Removing First Element:
[2, 3, 4, 5]
Program 2: Remove first element using Array.copyOfRange() java method
- In this program to remove the first element from the array, we are using Arrays.copyOfRange() method.
- Syntax of method is copyOfRange(int[] original_array, int from_index, int to_index).
- Here we will be passing the start index 1, so it will copy all the elements from 1 to the length of the array.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Java Program to delete First element from Array");
System.out.print("Enter the size of array: ");
int size = sc.nextInt();
int arr[] = new int[size];
for(int i=0; i<size; i++) {
System.out.print("Please give value for index "+ i +" : ");
arr[i] = sc.nextInt();
}
int newArr[] = Arrays.copyOfRange(arr, 1, arr.length);
System.out.println("New Array After Removing First Element: ");
System.out.println(Arrays.toString(newArr));
}
}
Output
Java Program to delete First element from Array
Enter the size of array: 4
Please give value for index 0 : 2
Please give value for index 1 : 4
Please give value for index 2 : 6
Please give value for index 3 : 8
New Array After Removing First Element:
[4, 6, 8]
Here we have seen two ways to remove the first element from an array. Hope this program is now clear to you.