OneBite.Dev - Coding blog in a bite size

insert an element at the beginning of an array in java

Code snippet on how to insert an element at the beginning of an array in java

  public static int[] insertElementAtBeginning(int element, int[] arr){ 
    int n = arr.length; 
    int[] newarr = new int[n + 1]; 
  
    newarr[0] = element; 
  
    for (int i = 0; i < n; i++) { 
      newarr[i + 1] = arr[i]; 
    } 

    return newarr; 
  } 

This code will insert an element at the beginning of an array in Java. It takes two arguments, an int element and an int array arr. The new array, newarr, is declared with a length of one more than the given array. The first index of the new array is set to the given element, and the remaining elements of the original array are copied to the new array, starting from index 1. Finally, the new array is returned.

java