56

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;
} 
Siqi Lin
  • 1,237
  • 1
  • 10
  • 25
Melinda
  • 577
  • 1
  • 5
  • 3
  • 3
    I think this [method](http://stackoverflow.com/questions/2393906/how-do-i-make-my-swap-function-in-java/20600020#20600020) is the closest you can get to a swap function in Java. – dansalmo Jun 25 '14 at 16:20
  • I found this article trying to figure out the same thing. [link](http://www.programmingsimplified.com/java/source-code/java-program-swap-numbers) – Jaca Feb 05 '15 at 05:40
  • This comes down to the impossible "pass primitive by reference": http://stackoverflow.com/questions/4319537/how-do-i-pass-a-primitive-data-type-by-reference – Ciro Santilli OurBigBook.com Apr 13 '15 at 06:41
  • Instead of simply giving a swap method, I'd give you [this article](http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html). It explains how to make a swap-method, but also explains how not to make it, and why it is not possible in the form you expect it, due to the fact Java is only pass-by-value (unlike C/C++) – Bozho Sep 02 '10 at 07:14
  • wrong answer.. java is not only pass by value.. When you pass a none-native value you're passing a pointer. If you have to new it, it's a pointer. http://javadude.com/articles/passbyvalue.htm – baash05 Mar 07 '12 at 10:48
  • 2
    you are passing a reference to the object - yes, but the reference is copied. "pass reference by value" is probably a better description. You can't change the reference that was passed, you can only change the target obejct – Bozho Mar 07 '12 at 11:03
  • C is just as much pass-by-value as Java is. – Buge May 11 '15 at 02:09
  • @Buge Not in the sense being discussed here. In C, as you probably know, it is possible to pass a pointer to ANYTHING, including a pointer to a variable location (not the variable's value; its location; a pointer-to-a-pointer). The result can be used as a "reference", that is, as the ability to modify what was pointed to by the source variable. As such, it is trivial to write a swap function in C. Anyone coming from C (or C++, C#, etc.) who attempts to write a swap function in Java, in the same way they would in C, finds that it can't be done (that way). – ToolmakerSteve Sep 09 '15 at 17:51
  • This question does not make much sense with no given context. In which context would you need such a swap function in java? – SpaceTrucker Feb 22 '16 at 09:25

19 Answers19

102

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);
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 17
    You'd hire someone who would write code that obscure? Maybe if they would then explain why they would never, ever actually *do* that in production code. – ToolmakerSteve Sep 09 '15 at 19:53
  • 2
    plus one for the trick, minus one for the fact it cannot be widely use in production without some good explanation. It cannot be enclosed in separate method, can it? – Bart Feb 24 '16 at 14:21
  • See here http://stackoverflow.com/questions/1363186/is-it-possible-to-write-swap-method-in-java/16826296#16826296 to learn how it works. – marcus Apr 05 '17 at 21:39
  • Thank you for this. Not having had Java as my primary language for a long time, I misunderstood part of the grammar. I thought one change Java had made from C/C++ was that assignments are not expressions. In fact, the change was that Java introduced a proper boolean type that can't be used interchangeably with integers, so you can't use an assignment in an if statement that does not return a boolean. Assignments return whatever type is involved in the assignment and they return the right hand side of the assignment expression. – froggythefrog Nov 22 '18 at 18:25
  • @GabrielŠčerbák I would make the caveat that if the employee who uses this can express it in such a way that it's clear a swap is being performed, then they should be applauded. The downside of this solution is the downside of trying to make a swap function in Java in the first place. You can't actually swap the basic types without stuffing them into an object or array first. :/ – froggythefrog Nov 22 '18 at 18:31
  • It's a bad advice in general. The method does not work in C++, because the order of evaluation of parameters is unspecified. So you learn a bad pattern here. – 0kcats Mar 29 '23 at 17:53
41

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

Prateek Joshi
  • 3,929
  • 3
  • 41
  • 51
  • 13
    because this does not answer the question. the question is about an independent function which can take two variables as argument and swaps them. – mightyWOZ Aug 20 '16 at 10:19
41

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;
}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • Since I am doing some sorting algorithms, I have array of ints. Do I need to typecast normal ints to AtomicInteger before calling swap? – Melinda Sep 02 '10 at 07:23
  • if you want to sort an array of ints, use Arrays.sort() http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5b%5d%29 – Sean Patrick Floyd Sep 02 '10 at 07:26
  • btw there's no way to typecast a primitive type to an object, but AtomicInteger has a constructor with an int – Sean Patrick Floyd Sep 02 '10 at 07:35
  • 1
    @Melinda: Arrays.sort is the answer, but if you want to swap two simple values follow the ol'good method: `int aux = b; b = a; a = aux;` – helios Sep 02 '10 at 07:37
  • But one may not always want to sort only ints, let alone only sort primitives. The real "will always work in Java" answer is your swap method using setters and getters. It worked for me and was a big help, thank you. – Benjamin R Oct 22 '14 at 08:03
11

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

Oleg Mikhailov
  • 5,751
  • 4
  • 46
  • 54
  • Let me swap double a = 1.0e17 and b = 1.0. Oops... It does not work. I think it will be worse in C++, where it would not work for any type or value. – 0kcats Mar 29 '23 at 17:45
5

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.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
  • 1
    Integer objects are immutable, so that won't work either. – Michael Borgwardt Sep 02 '10 at 07:16
  • 2
    Integers won't help, they are immutable. You need a container, either AtomicInteger (see my answer) or a 1-element List or array or any such thing – Sean Patrick Floyd Sep 02 '10 at 07:16
  • 1
    Again, Integer objects will be passed by value. This won't work either. http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html – Lunivore Sep 02 '10 at 07:16
  • 4
    @Lunivore: no, `Integer` objects are not passed by value. They are not passed at all. A **reference** *to an `Integer` object* will be passed by value. You can only pass references and primitive values in Java, never objects! – Joachim Sauer Sep 02 '10 at 07:39
  • Sorry. I was being lazy, and your description is far more accurate. In my defence, the URL explains it very well, even for objects which aren't immutable. – Lunivore Sep 02 '10 at 11:24
3

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;
}
PowerApp101
  • 1,798
  • 1
  • 18
  • 25
3

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]);   
} 
Landei
  • 54,104
  • 13
  • 100
  • 195
2

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.

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • It's not possible to swap two anythings by passing them into a method as parameters - not just primitives. – Lunivore Sep 02 '10 at 07:25
  • @Lunivore I thought that objects where passed by reference. So, in that case, why couldn't you swap their references? – Cristian Sep 02 '10 at 07:33
  • @Cristian: not correct: java objects are references that are passed by value. That's a difference – Sean Patrick Floyd Sep 02 '10 at 07:43
  • 1
    C also uses pass-by-value, only C++ has pass-by-reference. Even in the example given it passes the value of both pointers. That's why not having pass-by-reference doesn't have anything to do with this limitation in Java. – Trinidad Jan 27 '17 at 18:13
2

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;
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
  • True. And even interesting. But its more coding than inline swap using a temp variable. Perhaps would be good to point out that *if* a programmer is willing to carry the two values around in some object, *then* they can be swapped within that object. However, I can't think of any algorithms where that helps in practice. – ToolmakerSteve Sep 09 '15 at 20:33
1

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/

Sekhar Ray
  • 31
  • 1
1

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;
}
Ming-Tang
  • 17,410
  • 8
  • 38
  • 76
1

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

Bart
  • 2,167
  • 2
  • 15
  • 21
  • Not sure why this got downvoted as it's actually accurate. If you have those two values and you want to swap them, you can inline the method and it works just fine - but I agree, I can't really see why you'd need it in Java either. – Lunivore Sep 02 '10 at 11:26
  • Thanks. I was also suprised. It may be too laconic, but the code indicates C-like coding style which totally isn't the way to do things in Java. – Bart Sep 02 '10 at 11:35
  • 6
    A sweeping statement like "You really don't need that swap in Java" merits a downvote. The utility of swap *as a programming concept* is indisputable. There are numerous algorithms in which `swap` is a key step. If Bart wishes not to be downvoted, he needs to provide an alternative solution, for situations where `swap` is traditionally used in algorithms (as several other answers do, however incompletely). – ToolmakerSteve Sep 09 '15 at 20:18
1

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.

Lunivore
  • 17,277
  • 4
  • 47
  • 92
1

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.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
0

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.

  • This doesn't work. You need to read the question more carefully and read some of the other answers. – Andrew Martin Aug 21 '13 at 21:13
  • 1
    Try to do carefully @AndrewMartin. Because I has worked without any problems. – Yunus Seçgin Aug 22 '13 at 21:23
  • 3
    You've missed the point of the question. The OP was asking how to do a swap in a method _like in C_. Java _cannot_ do that, as it passes by value. If a swap is done in a method, it cannot be stored (unless values are returned). If two values were passed into a method and your code was executed, it wouldn't store the results out of the method. Read the question against and some of the other answers. – Andrew Martin Aug 22 '13 at 22:00
0
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);
    }
}
shaedrich
  • 5,457
  • 3
  • 26
  • 42
0

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
Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
-1
//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;
        }
}
-2
  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);
    }
  }