Course contentsShow
← Java
Lesson 266 of 2,8706. ArraysFree lesson

Arrays.sort: Sorting Primitive Arrays

Sorting arrays of primitives in ascending order using the built-in sort method.

Arrays.sort: Sorting Primitive Arrays

What you'll learn: How to use Java's built-in Arrays.sort() method to arrange primitive array elements in ascending order.

The Core Idea

Sorting means arranging elements in a specific order—typically from smallest to largest (ascending). While you could write your own sorting logic with loops and conditionals, Java provides a ready-made solution in the Arrays class: the sort() method.

Think of it like organizing a deck of numbered cards. Instead of manually comparing and swapping cards one-by-one, you have a helper who instantly arranges them in order for you.

Using Arrays.sort()

The method signature is simple:

Arrays.sort(arrayName);

This sorts the entire array in-place, meaning the original array is modified. The elements are arranged in ascending order (smallest to largest).

Example with Integers

int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
// numbers is now: {1, 2, 5, 8, 9}

for (int n : numbers) {
    System.out.print(n + " "); // Output: 1 2 5 8 9
}

Works with All Primitive Types

double[] prices = {19.99, 5.50, 12.00};
Arrays.sort(prices);
// prices is now: {5.5, 12.0, 19.99}

char[] letters = {'z', 'a', 'm', 'b'};
Arrays.sort(letters);
// letters is now: {'a', 'b', 'm', 'z'}

Important Points

  • The sorting happens in-place: your original array changes.
  • Ascending order only (for primitives).
  • Efficient and tested—no need to write your own sorting algorithm.

Key Takeaway: Use Arrays.sort(array) to quickly sort any primitive array in ascending order; the original array is modified directly.