Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a basic swap function in Java [duplicate]

Tags:

java

swap

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; }  
like image 709
Melinda Avatar asked Sep 02 '10 07:09

Melinda


People also ask

Is there a swap function 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.

What is the syntax of swap ()?

What is the syntax of swap()? Clarification: The correct syntax of swap function is arr1. swap(arr2) i.e. one array calling swap() function with second array as parameter to swap function.

How do you swap two variables in Java?

Two variables can be swapped in one line in Java. This is done by using the given statement. x = x ^ y ^ (y = x); where x and y are the 2 variables.


1 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); } 
like image 183
Eng.Fouad Avatar answered Sep 20 '22 13:09

Eng.Fouad