Home >Java >javaTutorial >How to Sort an Integer Array in Java Using Arrays.sort()?
How to Sort an Array in Java
You've created an array of 10 random integers and now you want to sort them in ascending order and display them on the screen. Here's how to do it:
Add the following line before System.out.println in your main method:
Arrays.sort(array);
This line uses the Arrays.sort() method to sort the array in place, modifying its elements to be in ascending order.
Here's the updated code:
public static void main(String args[]) { int[] array = new int[10]; // Populate the array with random values for (int i = 0; i < 10; i++) { array[i] = ((int) (Math.random() * 100 + 1)); } // 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 above is the detailed content of How to Sort an Integer Array in Java Using Arrays.sort()?. For more information, please follow other related articles on the PHP Chinese website!