function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Karteek SKarteek S 

How to swap two numbers in apex

Steven NsubugaSteven Nsubuga
public void swap(integer a, integer b) {
	integer c = a;
	a = b;
	b = c;
}

 
Ajay K DubediAjay K Dubedi
Hi Karteek,

Check this code

public class SwappingClass 
{
 public static void swapmethod()
 {
     integer i=10, j=20;
     i=i+j;
     j=i-j;
     i=i-j;
     system.debug('check values of i = '+i);
     system.debug('check values of j = '+j);
 }
}

Thank You
Ajay Dubedi
megha agarwal 20megha agarwal 20
Apex class:

public class Swapnumbers {
    public void Swapnumbersfunction(Integer x , Integer y){
        x=x+y;
        y=x-y;
        x=x-y;
        system.debug('n1 value' +x); 
        system.debug('n2 value' +y); 
        
    }
}

Annoymous window:
Swapnumbers sn=new Swapnumbers();
sn.Swapnumbersfunction(6,3);
Malika Pathak 9Malika Pathak 9

Hi karteek,

public class SwapTwoNumber
{
 public static void swapNumber(integer x, integer y)
 {
System.debug("Before Swap number");
System.debug("x--> "+x);
System.debug(""Y--> "+y);
     integer z=0;
z=x;
x=y;
y=z;

System.debug("After Swap number");
System.debug("x--> "+x);
System.debug(""Y--> "+y);
     
 }
}

If you find this helpful mark it as the best answer.