In this Java programming tutorials, I am going to show you how to swap two arrays in Java.

Swap two Arrays Example :

Input 1 : Give an integer array from command line. array1 {1,,2,4,5,3,7}

Input 2 : Give an another integer array from command line. array2 {5,6,0,8,4,3}

Output : array1 : {5,6,0,8,4,3} and array2 : {1,,2,4,5,3,7}


package com.onlinetutorialspoint.javaprograms;

import java.util.Scanner;

public class SwappingTwoArrays {
    public static void main(String[] args) {
        Scanner input_size = new Scanner(System.in);
        System.out.println("Enter the Size of Arrays : ");
        int size = input_size.nextInt();
        int[] array1 = new int[size], array2 = new int[size], buffer = new int[size];
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the First Array of Elements: ");
        for (int i = 0; i < size; i++) {
            array1[i] = sc.nextInt();
        }
        System.out.println("Enter the Second Array of Elements: ");
        for (int i = 0; i < size; i++) {
            array2[i] = sc.nextInt();
        }
        System.out.println("Before Swapping");
        System.out.println("First Array: ");
        for (int i = 0; i < size; i++) {
            System.out.print(array1[i]);
        }
        System.out.println("\nSecond Array: ");
        for (int i = 0; i < size; i++) {
            System.out.print(array2[i]);
        }
        for (int i = 0; i < size; i++) {
            buffer[i] = array1[i];
            array1[i] = array2[i];
            array2[i] = buffer[i];
        }
        System.out.println("\nArrays after Swapping");
        System.out.println("First Array: ");
        for (int i = 0; i < size; i++) {
            System.out.print(array1[i]);
        }
        System.out.println("\nSecond Array: ");
        for (int i = 0; i < size; i++) {
            System.out.print(array2[i]);
        }
    }
}

Output :

Enter the Size of Arrays :
5
Enter the First Array of Elements:
1
5
6
9
8
Enter the Second Array of Elements:
5
6
4
2
8
Before Swapping
First Array:
15698
Second Array:
56428
Arrays after Swapping
First Array:
56428
Second Array:
15698

Happy Learning 🙂