Java Program Switch or Swap Two Arrays – In this program we will swap the given arrays a and b.
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
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,
Java Array Programs
Java Program Switch or Swap Two Arrays