vendredi 6 avril 2012

Swapping numbers in java, pass-by-value VS pass-by-reference

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;
If we call this function to try to swap numbers, the numbers won't be changed.
There is an example of swapping numbers in this link:, but it's confusing for beginners.

public class Swapping{
  static void swap(int i,int j){
  int temp=i;
  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);

This example doesn't mention that after we call the method swap, the numbers will return to their original values after this call.
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.

Aucun commentaire:

Enregistrer un commentaire