w3resource

Java: Insert an element into an array

Java Array: Exercise-9 with Solution

Write a Java program to insert an element (specific position) into an array.

Pictorial Presentation:

Java Array Exercises: Insert an element into an array

Sample Solution:

Java Code:

// Import the Arrays class from the java.util package.
import java.util.Arrays; 

// Define a class named Exercise9.
public class Exercise9 {
    
    // The main method where the program execution starts.
    public static void main(String[] args) {
        // Declare and initialize an integer array 'my_array'.
        int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};
        
        // Define the position where the new element will be inserted.
        int Index_position = 2;
        
        // Define the value of the new element to be inserted.
        int newValue = 5;

        // Print the original array using Arrays.toString() method.
        System.out.println("Original Array : " + Arrays.toString(my_array));     
        
        // Loop to shift elements to make space for the new element.
        for (int i = my_array.length - 1; i > Index_position; i--) {
            my_array[i] = my_array[i - 1];
        }
        
        // Insert the new element at the specified position.
        my_array[Index_position] = newValue;
        
        // Print the modified array with the new element.
        System.out.println("New Array: " + Arrays.toString(my_array));
    }
}

Sample Output:

Original Array : [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]                                                     
New Array: [25, 14, 5, 56, 15, 36, 56, 77, 18, 29] 

Flowchart:

Flowchart: Java exercises: Insert an element into an array

Java Code Editor:

Previous: Write a Java program to copy an array by iterating the array.
Next: Write a Java program to find the maximum and minimum value of an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/array/java-array-exercise-9.php