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 read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.