Swapping data in Arrays using Temp variables – Java

What it does: 

A program that swaps data which has been predefined into an array. It uses temp variables to do so. It changes the data at position 0 with the data at position 3. Prints out at the end so the change can be seen.


 * Created with IntelliJ IDEA.
 * User: Zara
public class SwapingDataArrays
 public static void main(String[] args)
 String [] names= {"Mary", "Kaye", "Eyup", "Santos"};
 String [] gender = {"Female", "Male", "Male", "Male"};
 int [] age = {12,9,10,24};

//Declaring temp arrays
 String tempName, tempGender;
 int tempAge;

 // assigning temp variables to arrays
 tempName = names[0];

tempGender = gender[0];

tempAge = age[0];

 // Swaping over the data
 names [0] = names[3];

gender[0] = gender[3];

age[0] = age[3];

 //Setting the array to temp variable
 names[3] = tempName;

gender[3] = tempGender;

age[3] = tempAge;

//Print out
 System.out.println(names[0] + " " +names[3]);
 System.out.println(gender[0] + " " +gender[3]);
 System.out.println(age[0] + " " +age[3]);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s