How to write a basic swap function in Java

JavaSwap

Java Problem Overview


I am new to java. How to write the java equivalent of the following C code.

void Swap(int *p, int *q)
{
   int temp;
   temp = *p;
   *p = *q;
   *q = temp;
} 

Java Solutions


Solution 1 - Java

Here is one trick:

public static int getItself(int itself, int dummy)
{
    return itself;
}

public static void main(String[] args)
{
    int a = 10;
    int b = 20;
    
    a = getItself(b, b = a);
}

Solution 2 - Java

Sorting two ints

The short answer is: you can't do that, java has no pointers.

But here's something similar that you can do:

public void swap(AtomicInteger a, AtomicInteger b){
    // look mom, no tmp variables needed
    a.set(b.getAndSet(a.get()));
}

You can do this with all kinds of container objects (like collections and arrays or custom objects with an int property), but just not with primitives and their wrappers (because they are all immutable). But the only way to make it a one-liner is with AtomicInteger, I guess.

BTW: if your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int):

Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged.)

Parameters:
    list - The list in which to swap elements.
    i - the index of one element to be swapped.
    j - the index of the other element to be swapped. 

Sorting an int[] array

apparently the real objective is to sort an array of ints. That's a one-liner with Arrays.sort(int[]):

int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);

To check the output:

System.out.println(Arrays.toString(arr));
// [1, 2, 3, 19, 25, 378]

And here is a simple helper function to swap two positions in an array of ints:

public static void swap(final int[] arr, final int pos1, final int pos2){
    final int temp = arr[pos1];
    arr[pos1] = arr[pos2];
    arr[pos2] = temp;
}

Solution 3 - Java

Here's a method to swap two variables in java in just one line using bitwise XOR(^) operator.

class Swap
{
   public static void main (String[] args)
   {
      int x = 5, y = 10;
      x = x ^ y ^ (y = x);
      System.out.println("New values of x and y are "+ x + ", " + y);
   }
} 

Output:

New values of x and y are 10, 5

Solution 4 - Java

Use this one-liner for any primitive number class including double and float:

a += (b - (b = a));

For example:

double a = 1.41;
double b = 0;
a += (b - (b = a));
System.out.println("a = " + a + ", b = " + b);

Output is a = 0.0, b = 1.41

Solution 5 - Java

There are no pointers in Java. However, every variable that "contains" an object is a reference to that object. To have output parameters, you would have to use objects. In your case, Integer objects.

So you would have to make an object which contains an integer, and change that integer. You can not use the Integer class, since it is immutable (i.e. its value cannot be changed).

An alternative is to let the method return an array or pair of ints.

Solution 6 - Java

In cases like that there is a quick and dirty solution using arrays with one element:

public void swap(int[] a, int[] b) {
  int temp = a[0];
  a[0] = b[0];
  b[0] = temp;
}

Of course your code has to work with these arrays too, which is inconvenient. The array trick is more useful if you want to modify a local final variable from an inner class:

public void test() {
  final int[] a = int[]{ 42 };  
  new Thread(new Runnable(){ public void run(){ a[0] += 10; }}).start();
  while(a[0] == 42) {
    System.out.println("waiting...");   
  }
  System.out.println(a[0]);   
} 

Solution 7 - Java

What about the mighty IntHolder? I just love any package with omg in the name!

import org.omg.CORBA.IntHolder;

IntHolder a = new IntHolder(p);
IntHolder b = new IntHolder(q);

swap(a, b);

p = a.value;
q = b.value;

void swap(IntHolder a, IntHolder b) {
	int temp = a.value;
	a.value = b.value;
	b.value = temp;
}

Solution 8 - Java

Java uses pass-by-value. It is not possible to swap two primitives or objects using a method.

Although it is possible to swap two elements in an integer array.

Solution 9 - Java

Snippet-1

public int[] swap1(int[] values) {
  if (values == null || values.length != 2)
    throw new IllegalArgumentException("parameter must be an array of size 2");
  int temp = values[0];
  values[0]=values[1];
  values[1]=temp;
  return values;
}

Snippet-2

public Point swap2(java.awt.Point p) {
  if (p == null)
    throw new NullPointerException();
  int temp = p.x;
  p.x = p.y;
  p.y = temp;
  return p;
}

Usage:

int[] values = swap1(new int[]{x,y});
x = values[0];
y = values[1];

Point p = swap2(new Point(x,y));
x = p.x;
y = p.y;

Solution 10 - Java

You cannot use references in Java, so a swap function is impossible, but you can use the following code snippet per each use of swap operations:

T t = p
p = q
q = t

where T is the type of p and q

However, swapping mutable objects may be possible by rewriting properties:

void swap(Point a, Point b) {
  int tx = a.x, ty = a.y;
  a.x = b.x; a.y = b.y;
  b.x = t.x; b.y = t.y;
}

Solution 11 - Java

You have to do it inline. But you really don't need that swap in Java.

Solution 12 - Java

Your swap function is essentially changing the values in two pieces of memory. Anything referencing those bits of memory will now get different values.

In Java there aren't really pointers, so this won't work. Instead, references are held on objects, and you can only change stuff inside the objects. If you need to reference one object in two places, so that you can pass the same values around the system and have things react to them changing, try something like the repository pattern or dependency injection.

We can only guess at why you needed this code in C. The only advice I can give is to think about the changes to the objects which you want to achieve, preferably add a method on the actual objects rather than pulling their internals out, and call that method instead. If this doesn't help you, try posting the calling code as we'll probably have a good idea of how to solve the real problem Java-style.

Solution 13 - Java

Java is pass by value. So the swap in the sense you mean is not possible. But you can swap contents of two objects or you do it inline.

Solution 14 - Java

You can swap variables with or without using a temporary variable.

Here is an article that provides multiple methods to swap numbers without temp variable :

http://topjavatutorial.com/java/java-programs/swap-two-numbers-without-a-temporary-variable-in-java/

Solution 15 - Java

You can easily write one yourself.

given:

int array[]={1,2};

you do:

int temp=array[0];
array[0]=array[1];
array[1]=temp;

And you're done. 3 lines of code.

Solution 16 - Java

public class swaptemp {
	public static void main(String[] args) {
		String s1="10";
    	String s2="20";
    	String temp;
    	System.out.println(s1);
    	System.out.println(s2);
   
    	temp=Integer.toString(Integer.parseInt(s1));
    	s1=Integer.toString(Integer.parseInt(s2));
    	s2=Integer.toString(Integer.parseInt(temp));

    	System.out.println(s1);
    	System.out.println(s2);
	}
}

Solution 17 - Java

Swapping by using pointer is not possible in java. However, you can implement swapping by passing array containing two objects.

Code goes like this:

public class Swap {
    public static void swap(String [] a){
        String temp;
        temp = a[0];
        a[0] = a[1];
        a[1] = temp;
    }
    public static void main(String [] args){
        String [] foo = new String[2];
        foo[0] = "str1";
        foo[1] = "str2";
        swap(foo);
        System.out.println("First value: "+ foo[0]);
        System.out.println("Second value: "+ foo[1]);
    }
}

Output:

First value: str2
Second value: str1

Solution 18 - Java

//here is also another answer:
class SwapDemo{
	static int a=1, b=2 ;
	public static void main(String [] args){
		Swap swp = new Swap();
		swp.swaps(x,y);
		System.out.println( " a (was 1)now is " + a + " b (was 2) now is " + b);
	}
}
class Swap{
	void swaps(int c, int d){
	        SwapDemo f = new SwapDemo();
	        f.a = c;
	        f.a = d;
        }
}

Solution 19 - Java

  class Swap2Values{
    public static void main(String[] args){
       int a = 20, b = 10;

       //before swaping
       System.out.print("Before Swapping the values of a and b are: a = "+a+", b = "+b);

       //swapping
       a = a + b;
       b = a - b;
       a = a - b;

       //after swapping
      System.out.print("After Swapping the values of a and b are: a = "+a+", b = "+b);
    }
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMelindaView Question on Stackoverflow
Solution 1 - JavaEng.FouadView Answer on Stackoverflow
Solution 2 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 3 - JavaPrateek JoshiView Answer on Stackoverflow
Solution 4 - JavaOleg MikhailovView Answer on Stackoverflow
Solution 5 - JavaSjoerdView Answer on Stackoverflow
Solution 6 - JavaLandeiView Answer on Stackoverflow
Solution 7 - JavaPowerApp101View Answer on Stackoverflow
Solution 8 - JavacodaddictView Answer on Stackoverflow
Solution 9 - JavaAndreas DolkView Answer on Stackoverflow
Solution 10 - JavaMing-TangView Answer on Stackoverflow
Solution 11 - JavaBartView Answer on Stackoverflow
Solution 12 - JavaLunivoreView Answer on Stackoverflow
Solution 13 - JavafastcodejavaView Answer on Stackoverflow
Solution 14 - JavaSekhar RayView Answer on Stackoverflow
Solution 15 - JavaYunus SeçginView Answer on Stackoverflow
Solution 16 - Javauser5962065View Answer on Stackoverflow
Solution 17 - JavaNabin BhandariView Answer on Stackoverflow
Solution 18 - JavaTepken VannkornView Answer on Stackoverflow
Solution 19 - JavaTepken VannkornView Answer on Stackoverflow