Is it possible to write a swap method in Java?

Here's the question: write a method that changes two variables. These two variables must be primitive. It does not have to be shared, for example. two int variables. Is there any way ?!

+44
java swap primitive-types
Sep 01 '09 at 15:42
source share
13 answers

Without using an array or no objects, this cannot be done within the framework of the method.

+42
Sep 01 '09 at 15:44
source share

While it is impossible to write a function that simply swaps two variables, you can write an auxiliary function that allows you to:

  • Exchange two variables with just one operator
  • No temporary variables in caller code
  • No primitives <boxes>
  • With multiple overloads (one of them uses generics), it works for any type

How could you do this:

 int returnFirst(int x, int y) { return x; } int a = 8, b = 3; a = returnFirst(b, b = a); // try reading this as a = b; b = a; System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8 

This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages โ€‹โ€‹where the evaluation order is undefined), so the order of execution:

  • The initial value of b is evaluated to be passed as the first argument to the function
  • The expression b = a expressed, and the result (the new value of b ) is passed as the second argument to the function
  • The function executes by returning the original value of b and ignoring its new value
  • You assign the result a

If returnFirst too long, you can choose a shorter name to make the code more compact (e.g. a = sw(b, b = a) ). Use this to impress your friends and confuse your enemies :-)

+43
May 30 '13 at 0:59
source share

Check out this JavaWorld article that explains this in detail:

http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

Changing two primitives will never work, because primitives are passed by value in Java. You cannot even write a method for exchanging two objects in this regard.

Like @Thomas, the only thing you could do is to have the primitives contained in other objects / arrays and modify them.

+18
Sep 01 '09 at 15:48
source share

You can create a universal version of the @marcus swap exchange method that swaps any number of objects of the same type:

 <T> T swap(T... args) { // usage: z = swap(a, a=b, b=c, ... y=z); return args[0]; } b = swap(a, a=b); z = swap(x, x=y, y=z); 
+3
Dec 15 '13 at 21:52
source share

Single line for any primitive numbers:

 a += (b - (b = a)); 
+3
May 17 '16 at 1:24
source share

In java5, the closest I can think of can help you:

The AtomicInteger class (and others) has atomic methods getAndSet() .

+2
01 Sep '09 at 15:48
source share

To write a swap method that replaces primitives, you will need to have the concept of โ€œoutsideโ€ variables, that is, variables whose values โ€‹โ€‹are passed to the calling context. C # has those, but you should still point out that they are outside of the variables.

+2
Sep 01 '09 at 15:53
source share

This function will replace two ints

 Integer[] swap(int a, int b){ return new Integer[]{b,a}; } 
+1
May 09 '13 at
source share

It uses a method that replaces two primitive variables

 private void swap(){ int a = 1; int b = 2; int temp = a; a = b; b = temp; } 

This may not be very useful though;)

Well, this can be done if the variables are class levels:

 public class MyClass{ // excuse horrible coding practice of public mutable fields public int a = 1; public int b = 2; public void swap(){ int temp = a; a = b; b = temp; } } 

Again, I do not understand what it could be

+1
Mar 04 '14 at 12:05
source share

I read the answers above, looking for an explanation of why it says that the exchange program cannot be written in java as it is written in C ++. I made the following path a screenshot of the program

+1
Jan 18 '16 at 9:37
source share

As Thomas Owens said. Perhaps you could do this in C by passing variables by reference, but afaik is not in Java without using objects.

0
Sep 01 '09 at 15:51
source share

Yes, using the method you can change two variables. But you must declare this method as empty parentheses, and then call it a reference (empty parentheses) . The following is an example illustrating the replacement of two variables using the method.

public class Swapping

{

 static String A="Apple"; static String B="Bat"; public static void swap() { String k; k=A; A=B; B=k; } public static void main(String[] args) { System.out.println("Before swapping"); System.out.println("A= "+A); System.out.println("B= "+B); swap(); System.out.println("After swapping"); System.out.println("A= "+A); System.out.println("B= "+B); } 

}

After compiling the above code, the output is as follows:

Before replacing

A = Apple

B = Baht

After replacement

A = Baht

B = Apple

// In the case of a call to the original source value, it changes if we make changes to the called method

0
Oct 01 '15 at 15:05
source share
 public class Swap { public static void main (String[]args) { int y = 5; int x = 4; int c; System.out.println("y = "+y); System.out.println("x = "+x); c=x; //c = 4 x=y; //x = 5; y=c; System.out.println("\n"); System.out.println("y= "+y); System.out.println("x= "+x); } } 
-four
Oct. 15 '12 at 17:22
source share



All Articles