-1

i start learn java, and i build 'swap' function that replaces numbers.

when i run this code, its not replace them.

how could i solve this problem?

public static void swap(double i, double j){
        double temp = i;
        i = j;
        j = temp;
}

this in the main:

double i = 1;
double j = 2;
System.out.println(i+" - "+ j);
swap(i, j);
System.out.println(i+" - "+ j);

in the Console i see:

1.0 - 2.0
1.0 - 2.0

and i need to see:

1.0 - 2.0
2.0 - 1.0
Doron Levi
  • 95
  • 5

2 Answers2

1

In Java, everything is passed by value, including primitive types. You have copies of i and j in your swap method. You did swap the values i and j, but only the local values i and j in the scope of your swap method. The i and j in main were not changed.

To swap the values, implement the swap code inline in the main method, not in a separate method.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

Java is pass by value, even for references. You are changing a copy of the original values, not the originals.

There is no way to implement a swap method in Java to do what you suggest.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130