Sorting Integers with Varargs in Java


Create a Java program to demonstrate a method with varargs that sorts a sequence of integers

  • The class SortNumbers contains a single static method sortNumbers that takes a variable number of integers as input (using varargs).
  • Inside the sortNumbers method, it first prints the given numbers using Arrays.toString(numbers).
  • It then sorts the numbers array using Arrays.sort(numbers), which sorts the array in ascending order.
  • After sorting, it prints the sorted numbers using Arrays.toString(numbers).
  • In the main method, the sortNumbers method is called with a list of integer values to demonstrate its functionality.

Source Code

import java.util.Arrays;
 
public class SortNumbers
{
	static void sortNumbers(int... numbers)
	{
		System.out.println("Given Numbers : " + Arrays.toString(numbers));
		Arrays.sort(numbers);
		System.out.println("Sorted Numbers : " + Arrays.toString(numbers));
	}
 
	public static void main(String[] args)
	{
		sortNumbers(80, 73, 65, 15, 39, 51);
	}
}

Output

Given Numbers : [80, 73, 65, 15, 39, 51]
Sorted Numbers : [15, 39, 51, 65, 73, 80]

Example Programs