Javatpoint Logo
Javatpoint Logo

How to Swap or Exchange Objects in Java

In Java, swapping or exchanging objects can be done by assigning one object's value to another object and vice versa. It can be done by using a temporary variable to hold the value of one object while it is being swapped with the value of another object.

It's important to note that they are not being swapped when swapping or exchanging objects in Java. Rather, their references are being swapped, so the objects remain the same but their positions in memory change. It can be useful in cases where you need to reorder a list or array without creating new objects.

Approach: Using concepts of OOPS

In Java, objects can be swapped or exchanged using concepts of OOPS, specifically by passing objects as parameters to methods. It can be achieved by creating a separate method to swap the objects or by defining a swap method within the class. The objects can be swapped by using temporary variables to store the values of one object and then assigning them to the other object.

Algorithm

  1. Create a Person class with name and age attributes and getter and setter methods for each attribute.
  2. Implement a static method swapPersons(Person p1, Person p2) that takes two Person objects as input parameters.
  3. Declare temporary variables to store the name and age values of p1.
  4. Assign the name and age values of p2 to p1, and assign the temporary name and age values of p1 to p2.
  5. Create two Person objects, print their original values, call the swapPersons method to swap them, and then print the swapped values.

Implementation

Filename: Person.java

Output:

Before swapping:
Person 1 - Name: John, Age: 25
Person 2 - Name: Sarah, Age: 30
After swapping:
Person 1 - Name: Sarah, Age: 30
Person 2 - Name: John, Age: 25

Approach: Using wrapper class

In Java, a wrapper class is a class that provides a way to use primitive data types as objects. It is used to convert primitive data types into objects and vice versa. It also provides additional methods to work with the data. For example, the wrapper class for int is Integer, for double is Double, and so on.

Algorithm

  1. Initialize two objects, a and b, with their respective values.
  2. Print the values of a and b before swapping.
  3. Create a temporary variable temp of the same type as the objects.
  4. Assign the value of a to temp.
  5. Assign the value of b to a.
  6. Assign the value of temp to b.
  7. Print the values of a and b after swapping.

Implementation

Filename: ObjectSwapExample.java

Output:

Before swapping:
a = 5
b = 10
After swapping:
a = 10
b = 5






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA