Java Arrays - sort() Method
The java.util.Arrays.sort() method is used to sort the specified array of objects into ascending order, according to the natural ordering of its elements.
Syntax
public static void sort(Object[] a)
Parameters
a |
Specify the array to be sorted. |
Return Value
void type.
Exception
Throws ClassCastException, if the array contains elements that are not mutually comparable (for example, strings and integers).
Example:
In the example below, the java.util.Arrays.sort() method is used to sort a specified Object array.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating an unsorted Object array Object MyArr[] = {10, 2, -3, 35, 56}; //printing array before sorting System.out.print("MyArr contains:"); for(Object i: MyArr) System.out.print(" " + i); //sort the array Arrays.sort(MyArr); //printing array after sorting System.out.print("\nMyArr contains:"); for(Object i: MyArr) System.out.print(" " + i); } }
The output of the above code will be:
MyArr contains: 10 2 -3 35 56 MyArr contains: -3 2 10 35 56
❮ Java.util - Arrays