- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to swap or exchange objects in Java?
Java uses call by value while passing parameters to a function. To swap objects, we need to use their wrappers. See the example below −
Example
public class Tester{ public static void main(String[] args) { A a = new A(); A b = new A(); a.value = 1; b.value = 2; //swap using objects swap(a,b); System.out.println(a.value +", " + b.value); Wrapper wA = new Wrapper(a); Wrapper wB = new Wrapper(b); //swap using wrapper of objects swap(wA,wB); System.out.println(wA.a.value +", " + wB.a.value); } public static void swap(A a, A b){ A temp = a; a = b; b = temp; } public static void swap(Wrapper wA, Wrapper wB){ A temp = wA.a; wA.a = wB.a; wB.a = temp; } } class A { public int value; } class Wrapper { A a; Wrapper(A a){ this.a = a;} }
Output
1, 2 2, 1
- Related Articles
- How to Enable Or Add Swap Space on Ubuntu 16.04
- Java program to swap two integers
- Java Program to Swap Two Numbers.
- Java Program to Swap Pair of Characters
- How to remove all objects except one or few in R?
- How to create wrapper objects in JShell in Java 9?
- How to Swap Two Numbers in Golang?
- Swap two variables in one line in Java
- How Java objects are stored in memory?
- How are Java objects stored in memory?
- How do we copy objects in java?
- Java program to swap two numbers using XOR operator
- Java Program to swap the case of a String
- How to swap variables with destructuring in JavaScript?
- How to swap two array elements in JavaScript?

Advertisements