Array Java Programs

Insert Element in Array at given Location

In this tutorial, we will learn to write a Java program to insert an element at a given position of an array. Our program will insert 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 types 9 to add an element 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 enters 10 at index 1, the output should be {9, 10, 2, 4, 8}.

Insert Element in Array at given Location in Java

import java.util.*;

public class ArrayExample {
	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]);
		}
	}
}

Explanation

For the given array {1, 2, 3, 4, 5, 6, }, the user enters element 7 to be added at index 2 of the array. Since arr [2] = arr [1], the elements at the second index become the third element of the array, leaving the second index empty and allowing any element to be added. Since the user has entered 7, 7 is placed at index 2 using arr[loc]= 7.

Output

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

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs