To write a java program to insert an element into an array.
- Create the class and declare the main method so that the JVM will identify the main program to run.
- Declare an array and get the length of the array from the user.
- Get the array elements from the user and store them in the array.
- From the user get the input element which is to be added to the array
- Print the array with the added element
- End the program.
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int len, p,ele;
Scanner sc = new Scanner(System.in);
System.out.print("Enter length of an array:");
len = sc.nextInt();
int arr[] = new int[len+1];
System.out.println("Enter "+len+" elements:");
for(int i = 0; i < len; i++)
{
arr[i] = sc.nextInt();
}
System.out.print("Enter the element which you want to insert:");
ele = sc.nextInt();
arr[len] = ele;
System.out.print("After inserting : ");
for(int i = 0; i <len; i++)
{
System.out.print(arr[i]+",");
}
System.out.print(arr[len]);
}
}
![image](https://private-user-images.githubusercontent.com/93427376/241614467-bba260c8-489a-4f90-b8c9-4140084f5458.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjIxNjIyMzQsIm5iZiI6MTcyMjE2MTkzNCwicGF0aCI6Ii85MzQyNzM3Ni8yNDE2MTQ0NjctYmJhMjYwYzgtNDg5YS00ZjkwLWI4YzktNDE0MDA4NGY1NDU4LnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA3MjglMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwNzI4VDEwMTg1NFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTk4N2VjOGIwZWMxODhkMDJlOTU4ZmRiNWZlZDM3MDU0N2ExYzA1OTIxMWZmOTcyMzVlNzI5NWJlMTk5YTgyNWUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.y7U5IH0nINx8zcGRfrFzVdvdCMqCyja_zu7nRcuML7c)
Thus an element is inserted in an array using java programming language.