Given below is a sample implementation:
class Array {
public static void swap(int i, int j, int[] array) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
/**
*
* Displays elements of the array from the end to the beginning
*/
public static void display(int[] array) {
// Use `for (int i =0; i <array.length; i++)` for forward navigation
for (int i = array.length - 1; i >= 0; i--) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
public class ArrayTest {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Array.display(arr);
Array.swap(0, 9, arr);
Array.display(arr);
}
}
Output:
10 9 8 7 6 5 4 3 2 1
1 9 8 7 6 5 4 3 2 10
Notice that the static
members are class members i.e. they are one per class as compared to non-static
members which are one per instance. Therefore, static
members should be accessed using the class name instead of using an instance e.g. Array.display
as shown above.
Side note (because it won't affect the execution of your program): You should always follow Java naming conventions e.g. the class, array
should be named as Array
and the class, arrayTest
should be named as ArrayTest
. Also, try to avoid a name which has already been used in standard Java library e.g. you should choose a name other than Array.
[Update]
As promised, posting below a different implementation:
import java.util.Random;
class Array {
int[] array;
Array(int size) {
array = new int[size];
// Initialise the array with random elements from 0 to 100
Random random = new Random();
for (int i = 0; i < size; i++) {
array[i] = random.nextInt(100);
}
}
public void swap(int i, int j) {
if (i < 0 || j > array.length - 1) {
System.out.println("Indices should be in the range of 0 to " + (array.length - 1));
return;
}
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
/**
*
* Displays elements of the array from the end to the beginning
*/
public void display() {
for (int i = array.length - 1; i >= 0; i--) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
public class ArrayTest {
public static void main(String[] args) {
Array arry = new Array(10);
arry.display();
arry.swap(0, 9);
arry.display();
arry.swap(0, 11);
}
}
Output from a sample run:
94 50 5 90 78 33 90 61 64 31
31 50 5 90 78 33 90 61 64 94
Indices should be in the range of 0 to 9
Note that these are just a couple of sample implementations. I hope, it will help how you write your own implementation as per your requirement. Feel free to comment in case of any doubt/issue.