Answers for "java array remove element at index"

1

Remove element from a specific index from an array in java

// remove element from a specific index from an array
import java.util.Arrays;
public class DeleteElementDemo
{
   // remove element method 
   public static int[] removeElement(int[] arrGiven, int index) 
   {
      // if empty 
      if(arrGiven == null || index < 0 || index >= arrGiven.length) 
      {
         return arrGiven; 
      }
      // creating another array one less than initial array 
      int[] newArray = new int[arrGiven.length - 1];
      // copying elements except index 
      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 };
      // printing given array 
      System.out.println("Given array: " + Arrays.toString(arrInput));
      // getting specified index 
      int index = 3;
      // print index 
      System.out.println("Index to be removed: " + index);
      // removing element 
      arrInput = removeElement(arrInput, index);
      // printing new array 
      System.out.println("New array: " + Arrays.toString(arrInput));
   }
}
Posted by: Guest on February-18-2021
5

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){
                // shifting elements
                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]);
        }                
    }
}
Posted by: Guest on April-29-2020

Code answers related to "java array remove element at index"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language