How to write a basic swap function in Java

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; } 
+45
java swap
Sep 02 '10 at 7:11
source share
19 answers

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); } 
+58
Oct 29 '13 at 6:46 on
source share

Sort two ints

Short answer: you cannot do this, java has no pointers.

But here is 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 (for example, collections and arrays or custom objects with int property), but just not with primitives and their wrappers (because they are all immutable). But the only way to make it one liner is with AtomicInteger, I think.

BTW: if your data is a list, the best way to share 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. 



Array Sort int []

Apparently, the real goal is to sort the array from int. This is single line 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 replace two positions in an ints array:

 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; } 
+36
Sep 02 '10 at 7:15
source share

Here we use the method of replacing two variables in java on only one line using the bitwise operator XOR (^) .

 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:

The new x and y values โ€‹โ€‹are 10, 5

+32
Jan 12 '16 at 19:41
source share

Use this single-line layer for any class of primitive numbers, 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 a = 0.0, b = 1.41

+6
May 17 '16 at 12:46
source share

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

So, you will need to create an object that contains an integer, and change that integer. You cannot use the Integer class because it is immutable (i.e., its value cannot be changed).

An alternative is to return the method to an array or int pairs.

+4
Sep 02 '10 at 7:13
source share

Java uses pass-by-value . The method does not allow the exchange of two primitives or objects using the method.

Although you can swap two elements in an integer array.

+2
Sep 02 '10 at 7:14
source share

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 = px; px = py; py = temp; return p; } 

Using:

 int[] values = swap1(new int[]{x,y}); x = values[0]; y = values[1]; Point p = swap2(new Point(x,y)); x = px; y = py; 
+2
Sep 02 '10 at 7:29
source share

You cannot use links in Java, so the swap function is not possible, but you can use the following code snippet for each use of swap operations:

 T t = p p = q q = t 

where T is type p and q

However, replacing mutable objects may be possible by overwriting properties:

 void swap(Point a, Point b) { int tx = ax, ty = ay; ax = bx; ay = by; bx = tx; by = ty; } 
+1
Sep 02 '10 at 7:14
source share

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

+1
02 Sep '10 at 7:17
source share

In such cases, there is a quick and dirty solution using single-element arrays:

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

Of course, your code should work with these arrays too, which is inconvenient. A massive trick is more useful if you want to change 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]); } 
+1
Sep 02 '10 at 7:26
source share

Your swap function significantly changes values โ€‹โ€‹in two parts of memory. Everything that refers to these bits of memory will now receive different values.

There are no pointers in Java, so this will not work. Instead, links are stored on objects, and you can only change things inside objects. If you need to reference one object in two places so that you can pass the same values โ€‹โ€‹to the system and respond to them, try something like a repository pattern or dependency injection .

We can only guess why you need this code in C. The only advice I can give is to think about the changes to the objects you want to achieve, it is preferable to add a method to real objects, rather than pulling their insides and call this method instead . If this does not help you, try sending the calling code, as we will probably have a good idea on how to solve the real Java-style problem.

+1
Sep 02 '10 at 7:27
source share

Java is passed by value. Thus, swap in the sense that you mean is impossible. But you can exchange the contents of two objects, or you do it inside.

+1
02 Sep '10 at 7:50
source share

What about the mighty IntHolder? I just like 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; } 
+1
Sep 15 '15 at 13:49
source share

You can change variables with or without a temporary variable.

Here is an article that offers several methods for exchanging numbers without the temp variable:

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

+1
04 Feb '16 at 3:59
source share

You can easily write it yourself.

Given:

 int array[]={1,2}; 

:

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

And you're done. 3 lines of code.

0
Aug 21 '13 at 21:08
source share
 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); } } 
0
Feb 22 '16 at 9:16
source share

Switching with a pointer is probably not in java. However, you can implement swapping by passing an array containing two objects.

The code is as follows:

 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 
0
May 31 '16 at 12:28
source share
 //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(); fa = c; fa = d; } } 
-one
Dec 08 2018-10-10
source share
  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); } } 
-2
Dec 18 '10 at 6:17
source share



All Articles