how to remove an index from an array java code example
Example 1: Remove element from a specific index from an array in java
import java.util.Arrays;
public class DeleteElementDemo
{
public static int[] removeElement(int[] arrGiven, int index)
{
if(arrGiven == null || index < 0 || index >= arrGiven.length)
{
return arrGiven;
}
int[] newArray = new int[arrGiven.length - 1];
for(int a = 0, b = 0; a < arrGiven.length; a++)
{
if(a == index)
{
continue;
}
newArray[b++] = arrGiven[a];
}
return newArray;
}
public static void main(String[] args)
{
int[] arrInput = { 2, 4, 6, 8, 10 };
System.out.println("Given array: " + Arrays.toString(arrInput));
int index = 3;
System.out.println("Index to be removed: " + index);
arrInput = removeElement(arrInput, index);
System.out.println("New array: " + Arrays.toString(arrInput));
}
}
Example 2: how to delete an element from an array in java
import java.util.Scanner;
public class ElemRemoval {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] intArr = {1, 2, 5, 12, 7, 3, 8};
System.out.print("Enter Element to be deleted : ");
int elem = in.nextInt();
for(int i = 0; i < intArr.length; i++){
if(intArr[i] == elem){
for(int j = i; j < intArr.length - 1; j++){
intArr[j] = intArr[j+1];
}
break;
}
}
System.out.println("Elements -- " );
for(int i = 0; i < intArr.length - 1; i++){
System.out.print(" " + intArr[i]);
}
}
}