Java Program Switch or Swap Arrays

By | April 14, 2021

Java Program Switch or Swap Two Arrays – In this program we will swap the given arrays a and b.

Java Program To Switch arrays or swap arrays

How This Program Will Work?

First of all we will check if the length that is size of the given two arrays is equal or not. If the size of arrays is equal then we can
proceed to perform array switch or array swapping.

Java Program Switching or Swapping One dimensional  Arrays

We will write a method named switchThem
which will take two arrays as parameters and swap them using for
loop. It will traverse the whole array one by one and shift each element of first array in second array and vice versa.

First, we will define and initialize two arrays a and b of 5 integers numbers like as follows:

Array a = 1,2,3,4,5

Array b = 100,200,300,400,500

Then we will pass these arrays a, b to the user defined method switchThem(a,b). This method will actually switch or swap the arrays physically using a temporary variable.

Java Program to Switch or Swap Arrays

public class SwitchArrays {
 
public static void switchThem (int[] first, int[] second)
{
 if (first.length == second.length)
 {
 // copy contents of first into temp
 int [] temp = new int[first.length];
 int t;
 for (int i=0; i<first.length; i++)
 {
  t = first[i];
 first[i]=second[i];
 second[i]=t;
 }
 }
 else
 {
 System.out.println("Arrays are of different "
 + "sizes and cannot be switched.");
 }
} 
    
    public static void main(String[] args) {
        // TODO code application logic here
        
        int b[]={100,200,300,400,500};
        int a[]={1,2,3,4,5};
        
        System.out.println("Before swap");
        System.out.println("Array a");
        for(int i=0;i<5;i++)
            System.out.print(a[i]+",");
        
         System.out.println("\nArray b");
        for(int i=0;i<5;i++)
            System.out.print(b[i]+",");
        System.out.println();
        //call method two switch arrays
        switchThem(a,b);
        System.out.println("--------------\nAfter swap");
        System.out.println("Array a");
        for(int i=0;i<5;i++)
            System.out.print(a[i]+",");
        
         System.out.println("\nArray b");
        for(int i=0;i<5;i++)
            System.out.print(b[i]+",");
        System.out.println();
        
    }
    
}

Output of array swapping program in Java

Before swap
Array a
1,2,3,4,5,
Array b
100,200,300,400,500,
--------------
After swap
Array a
100,200,300,400,500,
Array b
1,2,3,4,5,

 220 total views,  3 views today

Leave a Reply

Your email address will not be published. Required fields are marked *