codescracker


java

Java Program to Insert Element in Array



« Previous Program Next Program »


Insert Element in Array

To insert any element in an array in Java Programming, you have to ask to the user to enter the array size and array elements, after storing the array elements in the array, now ask to the user to enter the element and position where he/she want to insert that element at desired position as shown in the following program.

Java Programming Code to Insert Element in Array

Following Java Program ask to the user to enter size and elements of the array, then ask to enter element/number to be insert, and at last again ask to enter the position (index number) where he/she want to insert the desired element in the array, so this program insert the desired element/number and display the new array on the screen after inserting the element/number:

/* Java Program Example - Insert Element in Array */
		
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int size, insert, i, pos;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
	   
       System.out.print("Enter Array Size : ");
       size = scan.nextInt();
	   
       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
	   
       System.out.print("Enter Element to be Insert : ");
       insert = scan.nextInt();
       System.out.print("At Which Position ? (Enter Index Number ) : ");
       pos = scan.nextInt();
       
       // now create a space at the required position
       
       for(i=size; i>pos; i--)
       {
           arr[i] = arr[i-1];
       }
	   
       arr[pos] = insert;
	   
       System.out.print("Element inserted Successfully..!!\n");
	   
       System.out.print("Now the New Array is :\n");
       for(i=0; i<size+1; i++)
       {
           System.out.print(arr[i]+ " ");
       }
   }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program insert element in array

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test