# Swap Elements of an Array in Java Example

by Dinesh Thakur Category: array

Algorithm for Swap Elements of an Array:

step 2: create two integer arrays a[],b[] of size y

step 3: initialize x=0

step 4: repeat through step-6 while (x < a.length)

step 6: x=x+l

step 7: reset x=0

step 8: repeat through step-11 while (x < a.length)

step 9: print a[x]

step 10: print one space

step 11: x=x+l

step 12: Reset x=0

step 13: repeat through step-15 while (x< y)

step 14: interchange a[x],b[x]

step 15: x=x+1

step 16: Exit

Here is the Java Example for Swap Elements of an Array:

```import java.util.Scanner;

public class SwapArray

{

public static void main(String args[])

{

int x,y;

Scanner s1=new Scanner(System.in);

System.out.print("Enter the Size of Array : ");

y=s1.nextInt();

int a[]=new int[y];

int b[]=new int[y];

System.out.println("\nEnter The Elements In First Array\n");

for(x=0;x<a.length;x++)

a[x]=s1.nextInt();

System.out.println("\nEnter The Elements In Second Array\n");

for(x=0;x<b.length;x++)

b[x]=s1.nextInt();

System.out.print("The Elements of First Array : ");

for(x=0;x<a.length;x++)

{

System.out.print(a[x]+" ");

}

System.out.print("\nThe Elements of second Array : ");

for(x=0;x<b.length;x++)

{

System.out.print(b[x]+" ");

}

System.out.print("\n");

for(x=0;x<y;x++)

{

a[x]=a[x]+b[x];

b[x]=a[x]-b[x];

a[x]=a[x]-b[x];

}

System.out.println("\nAfter swaping the Output is \n");

System.out.print("The Elements of First Array : ");

for(x=0;x<a.length;x++)

{

System.out.print(a[x]+" ");

}

System.out.print("\nThe Elements of second Array : ");

for(x=0;x<b.length;x++)

{

System.out.print(b[x]+" ");

}

System.out.print("\n");

}

}

```  Dinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles