To swap two values inside a Java array, you need to:
Here is a simple example of how to swap two elements in a Java array:
Before Swap: 10 20 30 40 50
After Swap: 10 40 30 20 50
public class SwapExample {
public static void main(String[] args) {
// Sample array
int[] arr = {10, 20, 30, 40, 50};
// Indexes of the two elements to be swapped
int index1 = 1; // Value 20 at index 1
int index2 = 3; // Value 40 at index 3
// Print the array before swapping
System.out.println("Before Swap: ");
for (int value : arr) {
System.out.print(value + " ");
}
// Swap the two values using a temporary variable
int temp = arr[index1]; // Store arr[index1] in temp
arr[index1] = arr[index2]; // Replace arr[index1] with arr[index2]
arr[index2] = temp; // Replace arr[index2] with temp (original arr[index1])
// Print the array after swapping
System.out.println("\n\nAfter Swap: ");
for (int value : arr) {
System.out.print(value + " ");
}
}
}
Before Swap:
10 20 30 40 50
After Swap:
10 40 30 20 50
{10, 20, 30, 40, 50}.index1 = 1 and index2 = 3, which means we are swapping the values 20 and 40.temp, the values at these two indices are swapped.{10, 40, 30, 20, 50}.You can swap any two values in the array by changing the index1 and index2 values accordingly.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.