Delete the last Element of an array in Java
In this tutorial, we are going to discuss how to delete the last element from an array in Java, We’ll look at the code for both static and dynamic declaration of the array.
Static Declaration
import java.util.Arrays; public class Static { public static void main(String[] args) { int array1[] = {11, 12, 13, 14}; int array2[] = Arrays.copyOf(array, array1.length - 1); System.out.println("Original : " + Arrays.toString(array1)); System.out.println("New Array : " + Arrays.toString(array2)); } }
In the above program we have declared two arrays:
Array1
Array2
We have initialized the first array as static by passing the elements along the declaration, The array1 has the actual and the Logical size the same//Logical Size: Number of elements present in the array.
Now we simply subtract one from the length of the array using the following function.
int array2[] = Arrays.copyOf(array, array1.length - 1);
Now we simply subtract one from the length of the array using the above-given function.
Output:
Original : [11, 12, 13, 14] New Array : [11, 12, 13]
Dynamic Declaration
import java.util.Arrays; public class Main1 { public static void main(String[] args) { int arr[] = new int[10]; arr[0]=(10); arr[1]=(7); arr[2]=(1); arr[3]=(9); int i; int LogicalSize=3; //Here in the given array altought the size of the array is 10 but the logical size of the array is 4 since there are only three elements present in the array. for(i=0;i<arr.length;i++) { if(i==LogicalSize) { arr[i]=(0); LogicalSize--; } } System.out.println("Original : " + Arrays.toString(arr)); } }
In the above program we have declared an array:
arr[]
We have initialized the array as Dynamic by declaring the size of the array along the declaration.
Next, we added four elements to the array and declared a variable called LogicalSizse to keep the track of the elements present in the array. We have also Declared a variable I for traversing the array.
Now using the for loop we traverse the array and if the value of I matches with the logical size that means we have reached the last element now we simply delete the element by setting the value as zero.
Since we deleted the last element, the LogicalSize is now decremented by 1.
Output:
Orignal : [10, 7, 1, 9, 0, 0, 0, 0, 0, 0] Result after deleting the last element : [10, 7, 1, 0, 0, 0, 0, 0, 0, 0]
Leave a Reply