Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why does this swap method not work? [duplicate]

Tags:

java

I have the following code:

public class Main {      static void swap (Integer x, Integer y) {         Integer t = x;         x = y;         y = t;     }      public static void main(String[] args) {        Integer a = 1;        Integer b = 2;        swap(a, b);        System.out.println("a=" + a + " b=" + b);     }  } 

I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?

like image 229
witzar Avatar asked Jan 11 '10 11:01

witzar


People also ask

Why swap does not work in Java?

The reason it didn't swap is because primitive variables are passed by value. This is what happens: Arguments are evaluated to values. Boxes for parameter variables are created.

Why swap function is not working?

You need to pass the memory address reference of the values so that the operation is done on the memory address of the original values. Swap needs to accept the memory reference of the values and store them in pointers which will perform operations to the original values' memory location.

What does swap () do in Java?

The swap() method of java. util. Collections class is used to swap the elements at the specified positions in the specified list. If the specified positions are equal, invoking this method leaves the list unchanged.

Can we swap two objects in Java?

The Java Collections Framework's classes have a built-in method to swap elements called swap(). The java. util is a utility class that contains static methods that can operate on elements like Lists from the Collection interface. Using the swap method is much easier than the example we discussed earlier.


2 Answers

This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit! (Not annoyed, just the title of the article :p )

To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)

    Thing tmp = a;     a = b;     b = tmp; 
like image 156
Svish Avatar answered Sep 24 '22 18:09

Svish


Everything in Java is passed by value and the values of variables are always primitives or references to object.

like image 24
Ravi Gupta Avatar answered Sep 24 '22 18:09

Ravi Gupta