I never thought about it, but I just discovered it is not possible to write a method to swap numbers in Java since Java is strictly pass-by-value, not pass by reference.
public void swapNumbers(int x, int y) { int temp = x; x = y; y = temp; }
There is an example of swapping numbers in this link: http://www.roseindia.net/java/beginners/swapping.shtml, but it's confusing for beginners.
public class Swapping{
static void swap(int i,int j){
int temp=i;
i=j;
j=temp;
System.out.println("After
swapping i = " + i + " j = " + j);
}
public static void main(String[] args){
int i=1;
int j=2;
System.out.prinln("Before swapping
i="+i+" j="+j);
swap(i,j);
}
}
The same operation is really simple in C++ which allows us to pass values by reference
void swapNumbers(double& a, double& b) { double temp = a; a = b; b = temp; }
Now, when we call this function, a and b will be swapped.*
double number1(5.5), number2(7.0) swapNumbers(number1, number2); cout << "First number : << number1 << endl; cout << " Second number :" << number2 << endl;
The output will be
First number : 7.0
Second number 5.5;
A reference is merely an alias, another name for the same variable. Hence, making operations on a variable will also change the variable value.