-1

I now know that to interchange array values you have to do something like this

String t = a[1];
a[1] = a[2];
a[2] = t;

My question is why is it not possible to just directly do

a[1] = a[2];
a[2] = a[1];

or

a[1] = 2;
a[2] = 1;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
69 420
  • 107
  • 6
  • You might want to look at https://stackoverflow.com/questions/10393690/is-it-possible-to-swap-two-variables-in-java and all the related questions about swapping values. – Progman May 23 '21 at 21:12
  • 2
    Perhaps you're missing the point that program statements are executed sequentially (in the absence of specific mechanisms for doing otherwise, like method calls, loops, etc.)? – iggy May 23 '21 at 21:22

2 Answers2

0

From Here

If you're swapping numbers and want a concise way to write the code without creating a separate function or using a confusing XOR hack, I find this is much easier to understand and it's also a one liner.

public static void swap(int[] arr, int i, int j) {
    arr[i] = (arr[i] + arr[j]) - (arr[j] = arr[i]);
}

What I've seen from some primitive benchmarks is that the performance difference is basically negligible as well.

This is one of the standard ways for swapping array elements without using a temporary variable, at least for integers.

StarshipladDev
  • 1,166
  • 4
  • 17
  • But why write that when you can use a temporary variable? What is the point? – iggy May 23 '21 at 21:20
  • @iggy Imagine you need to swap 100 different array parts within your program, and they all occur in different functions or threads. This method allows you to save 100 L.O.C in that case, as well as 100 variable declarations – StarshipladDev May 23 '21 at 21:22
  • And saving one stack variable per function or thread is negligible. It's not even clear it costs anything, since the stack space is reusable after the "three lines of code" that involve the variable. – iggy May 23 '21 at 21:25
-1

Program statements are executed sequentially. Therefore, as you replace one array value(x[0]) with the other (x[1]), then that statement occurs before any other.

To avoid this, you must store x[0] into a variable as the value at x[0] will be replaced before x[1] could be assigned, due to computer's sequential nature

StarshipladDev
  • 1,166
  • 4
  • 17