0
0
JavaHow-ToBeginner · 3 min read

How to Sort Array in Java: Simple Syntax and Examples

To sort an array in Java, use Arrays.sort(array) from the java.util.Arrays class. This method sorts the array elements in ascending order by default.
📐

Syntax

The basic syntax to sort an array is:

  • Arrays.sort(array); - sorts the entire array in ascending order.
  • Arrays.sort(array, fromIndex, toIndex); - sorts a range within the array from fromIndex (inclusive) to toIndex (exclusive).

You must import java.util.Arrays to use this method.

java
import java.util.Arrays;

public class SortSyntax {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 8, 1};
        Arrays.sort(numbers); // Sort whole array
        // Arrays.sort(numbers, 1, 3); // Sort from index 1 to 2
    }
}
💻

Example

This example shows how to sort an integer array and print the sorted result.

java
import java.util.Arrays;

public class SortExample {
    public static void main(String[] args) {
        int[] numbers = {10, 2, 33, 4, 15};
        Arrays.sort(numbers);
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}
Output
2 4 10 15 33
⚠️

Common Pitfalls

Common mistakes when sorting arrays in Java include:

  • Not importing java.util.Arrays, causing a compile error.
  • Trying to sort arrays of objects without implementing Comparable or providing a Comparator.
  • Assuming Arrays.sort() sorts in descending order by default (it sorts ascending).
  • Modifying the array while sorting, which can cause unexpected results.

For descending order, you must use a different approach, such as sorting and then reversing the array or using a Comparator with object arrays.

java
import java.util.Arrays;
import java.util.Collections;

public class DescendingSort {
    public static void main(String[] args) {
        Integer[] numbers = {5, 1, 9, 3};
        Arrays.sort(numbers, Collections.reverseOrder());
        for (Integer num : numbers) {
            System.out.print(num + " ");
        }
    }
}
Output
9 5 3 1
📊

Quick Reference

Summary tips for sorting arrays in Java:

ActionCode ExampleNotes
Sort entire array ascendingArrays.sort(array);Works for primitives and objects with Comparable
Sort part of arrayArrays.sort(array, fromIndex, toIndex);Sorts from fromIndex (inclusive) to toIndex (exclusive)
Sort objects descendingArrays.sort(array, Collections.reverseOrder());Array must be of type Object (e.g., Integer, not int)
Import neededimport java.util.Arrays;Required to use Arrays.sort()

Key Takeaways

Use Arrays.sort(array) to sort arrays in ascending order easily.
Import java.util.Arrays before using sort methods.
For descending order, use Arrays.sort with Collections.reverseOrder() on object arrays.
Primitive arrays sort ascending only; use wrapper classes for custom order.
Avoid modifying the array during sorting to prevent errors.