Home >Java >javaTutorial >How Can I Sort an Array of Integers in Java?
Sorting an Array in Java
Sorting an array involves organizing its elements in a specific order, typically from lowest to highest or vice versa. In your case, you aim to sort an array of 10 random integers from lowest to highest.
To achieve this, Java provides the Arrays.sort() method. This method takes an array as an argument and modifies it in-place, arranging its elements in ascending order (from lowest to highest).
In your code, you can incorporate Arrays.sort() as follows:
int[] array = new int[10]; // Populate the array with random values ... // Sort the array Arrays.sort(array); // Print the sorted array System.out.println(array[0] + " " + array[1] + " " + array[2] + " " + array[3] + " " + array[4] + " " + array[5] + " " + array[6] + " " + array[7] + " " + array[8] + " " + array[9]);
The Arrays.sort() method effectively sorts your array in ascending order. As a result, when you print the array, its elements will be displayed in the desired order.
The above is the detailed content of How Can I Sort an Array of Integers in Java?. For more information, please follow other related articles on the PHP Chinese website!