Sorting integer and string in natural order

Description

This program shows how to sort the integer and string using sort method of Arrays class that sorts the elements in natural order (Integer-ascending order, String-Alphabetical order). As the sort method is static the input array is modified instead of creating new array. Sorted elements can be accessed using enhanced for loop.

  • Filename: Sorting.java

import java.util.*;
class Sorting {
public static void main(String args[]) {
//Sorting Integer in natural order
int n[] = {40,20,29,65,74};
Arrays.sort(n);
System.out.println("Sorted list of Integer");
for(int i:n) {
System.out.println(i);
}
//Sorting String in natural order
String s[] = {"dog","cat","animal","bird","dove"};
Arrays.sort(s);
System.out.println("Sorted list of String");
for(String i:s) {
System.out.println(i);
}
}
}