Java Program to Insert Element in Array at given Location

In this tutorial, we will learn writing java program to insert an element at the given position of an array. Our program will add an element at the given position (index) of the given array.

For example

Case 1: if the given array is {1, 2, 3, 4} and the user gives input 9 to add at index 2.

            The output should be {1, 2, 9, 3, 4}.

Case 2: if the given array is {9, 2, 4, 8} and the user gives input 10 to add at index 1.

            The output should be {9, 10, 2, 4, 8}.

Insert Element at given Location in Array using Java

Program 1 : Using Iteration and increment

import java.util.*;  
public class InserAtLocation
{
	public static void main(String[] args) {
		int loc;
		Scanner sc = new Scanner(System.in);
        System.out.println("Java Program to insert element at given index of Array");
        System.out.print("Enter the size of array: ");
        int size = sc.nextInt();
        int arr[] = new int[size+1];
        for(int i=0; i<size; i++) {
            System.out.print("Please give value for index "+ i +" : ");
            arr[i] = sc.nextInt();
        }
        System.out.print("Enter the index where you want to insert:");
        loc = sc.nextInt();
        for (int i = size-1; i >= loc; i--){
            arr[i+1] = arr[i];
        }
        System.out.print("Enter the element to insert at index "+loc+" : ");
        arr[loc] = sc.nextInt();
        System.out.println("Array After Inserting "+ arr[loc] +" at index "+loc+" : ");
        for(int i=0; i<size+1; i++)
        {
            System.out.println(arr[i]);
        }
	}
}

Output

Java Program to insert element at given index of Array
Enter the size of array: 6
Please give value for index 0 : 4
Please give value for index 1 : 3
Please give value for index 2 : 2
Please give value for index 3 : 4
Please give value for index 4 : 1
Please give value for index 5 : 4
Enter the index where you want to insert:3
Enter the element to insert at index 3 : 6
Array After Inserting 6 at index 3 : 
4
3
2
6
4
1
4

Explanation

For the given array {1, 2, 3, 4, 5, 6, }, the user inputs element 7 to add at the index 2 of the array. So we iterate through the elements of the array 2 times and as arr[2] = arr[1], the elements at 2nd index  become the 3rd element of the array leaving 2nd index empty which is free to add any element , so as under input 7, so 7 is placed at index 2, using arr[loc]= 7.

Program Explanations

  1. Import and Class Definition:
    • The program starts by importing the java.util.* package, which includes the Scanner class used for capturing user input.
    • It defines a public class named InsertAtLocation.
  2. Main Method:
    • The program’s execution starts in the main method.
  3. User Input for Array Size:
    • The user is prompted to enter the size of the array. This size is read and used to initialize an array that is actually one element larger than the input size to accommodate the new element to be inserted later.
  4. Array Initialization:
    • The user is then asked to input values for each index of the array up to the original size (not including the extra space added for the new element).
  5. Input for Insertion Location and Validation:
    • The user specifies the index (loc) where they wish to insert a new element. The program assumes that the user input for location is valid (i.e., within the bounds of the array indices).
  6. Element Shifting:
    • To make space for the new element, the program shifts all elements from the specified index (loc) and beyond one position to the right. This shift starts from the last element (at size-1) and moves backward to the loc.
  7. Inserting the New Element:
    • The user is prompted to enter the new element to be inserted at the specified index. This value is directly assigned to arr[loc].
  8. Output the Modified Array:
    • Finally, the program prints out the entire array with the new element included, showcasing the array after the insertion.

Program 2: Using ArrayList for Dynamic Arrays

If frequent insertions are expected and array resizing is common, using ArrayList from Java’s Collections Framework is more appropriate due to its dynamic resizing capabilities.

import java.util.*;  
public class InserAtLocation
{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);  
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        
        System.out.print("Enter the index where you want to insert: ");
        int ind = sc.nextInt();   
        System.out.print("Enter the element to insert at index " + ind + " : ");   
        int elementToInsert = sc.nextInt();
        list.add(ind, elementToInsert);
        
        System.out.println("List after insertion: " + list);
        sc.close();  
	}
}

Output

Enter the index where you want to insert: 5
Enter the element to insert at index 5 : 4
List after insertion: [1, 2, 3, 4, 5, 4]

Program Explanation

  1. Import and Setup: The program imports necessary classes from the java.util package. It then creates an instance of the Scanner class to read user input from the console.
  2. List Initialization: An ArrayList of integers is initialized with the values {1, 2, 3, 4, 5}.
  3. User Input for Index: The program prompts the user to enter an index (ind) where they want to insert a new element into the list. The index is read using the Scanner.
  4. User Input for Element: The user is then asked to provide the integer value they want to insert at the specified index. This value is stored in elementToInsert.
  5. Insertion: The element is inserted into the list at the position specified by the user. The add method of ArrayList is used for this purpose, which shifts the element currently at that position (if any) and any subsequent elements to the right.
  6. Output: The program prints the list after the insertion to show how it has changed.
  7. Resource Management: Finally, the Scanner object is closed to free the resources associated with it.