an array swapp two elements using java? code example

Example 1: java array swap

public static void swap(int x, int y, int[] arr) {
  	int temp = arr[x];
  	arr[x] = arr[y];
  	arr[y] = temp;
}

Example 2: swapping with two variables in java

public class Exercise15 {
  public static void main(String[] args) {
     // int, double, float
   int a, b;
   a = 15;
   b = 27;
   System.out.println("Before swapping : a, b = "+a+", "+ + b);
   a = a + b;
   b = a - b;
   a = a - b;
   System.out.println("After swapping : a, b = "+a+", "+ + b);
 }
 
}

Tags:

Misc Example