w3resource

Java: Copy an array by iterating the array


8. Copy array using iteration

Write a Java program to copy an array by iterating the array.

Pictorial Presentation:

Java Array Exercises: Copy an array by iterating the array


Sample Solution:

Java Code:

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

// Define a class named Exercise8.
public class Exercise8 {
    
    // 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};
        
        // Declare and initialize a new integer array 'new_array' with the same size.
        int[] new_array = new int[10];     
 
        // Print the source array using Arrays.toString() method.
        System.out.println("Source Array : " + Arrays.toString(my_array));     
        
        // Loop to copy elements from the source array to the new array.
        for (int i = 0; i < my_array.length; i++) {
            new_array[i] = my_array[i];
        }
        
        // Print the new array containing copied elements.
        System.out.println("New Array: " + Arrays.toString(new_array));
    }
}

Sample Output:

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

Flowchart:

Flowchart: Java exercises: Copy an array by iterating the array


For more Practice: Solve these Related Problems:

  • Write a Java program to copy only even numbers from one array to another.
  • Write a Java program to deep copy a multidimensional array.
  • Write a Java program to copy alternate elements from one array to another.
  • Write a Java program to copy all non-zero elements from an array into a new array.

Go to:


PREV : Remove specific element from array.
NEXT : Insert element at specific position.

Java Code Editor:


What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.