Tell me please. How to make it work?

public static void main(String[] args) { int a = 0; int b = 3; swap(a, b); } public static void swap (int x, int y){ int tmp = x; x = y; y = tmp; } 
  • one
    Well, for example, to start writing what this code should do and what does not work in it. and why it should work as you think - Alexey Shimansky
  • @ Alexey Shimansky, in the code is a standard method for replacing the values ​​of two variables. The third is called tmp, as absolutely in all examples, and the word-name-method of swap also speaks for itself. - Pavel Bobrov
  • one
  • It doesn't matter what's written here. I could calmly call the swap method, which goes through the frogs in the lake. For a normal full-fledged question with a non-working code, it is always necessary to describe what it should do, what is wrong with it from your point of view and why (if any behavior is planned) should be like this - Alexey Shimansky

2 answers 2

Primitives are not passed by reference. In your code, only local copies on the stack in the swap method change. Can be wrapped in something. Often do this:

 public class IntRef { public int value; public IntRef (int val) { value = val; } } 

Then your code will be like this:

 public static void main(String[] args) { IntRef a = new IntRef(0); IntRef b = new IntRef(3); swap(a,b); } public static void swap (IntRef x, IntRef y){ int tmp = x.value; x.value = y.value; y.value = tmp; } 
  • then it's easier to do the Integer type - Alexey Shimansky
  • @ Alexey Shimansky yes. But I just wanted to show a conceptual approach. - Suvitruf
  • one
    @ Alexey Shimansky, and how does Integer help? - Qwertiy
  • one
    @Qwertiy Integer in any way. And java.util.concurrent.atomic.AtomicInteger will help, since the mutable type ^^ - Suvitruf
  • one
    Thank you very much, this example helped understand - Pavel Bobrov

There is no transfer of variables by reference in Java, so it is impossible to make a swap of two variables.

You can change the fields for objects, but it turns out that instead of two variables you need to have 2 fields (2 fields for one object, or 1 field for two objects), but this is clearly not something that you would have washed.