AI Hints
Home›Java Tutorial›The Enhanced for Loop, The Arrays Class and Searching an Array
Java · Lesson 50 of 120

The Arrays Class

Sort, print, fill.

⏱ 2 min read▶ Video at 1:02:37🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Java comes with a helper class called Arrays. It can print, sort, fill, and search arrays for you, in one line each.

  • A helper class
  • Print, sort, fill
  • One line each

Arrays helpers

Printing an array directly gives a strange code, not its values. Arrays dot to string prints it properly. Arrays dot sort sorts it, smallest first. Arrays dot fill puts one value into every box. Strings sort too, but capital letters come before small ones. Run it. The first line is unreadable. Then the numbers, then sorted. Four nines. And Apple comes first, because of its capital A.

Main.javajava
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        int[] nums = {42, 7, 19, 3, 25};
        System.out.println(nums);
        System.out.println(Arrays.toString(nums));
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));
        int[] filled = new int[4];
        Arrays.fill(filled, 9);
        System.out.println(Arrays.toString(filled));
        String[] words = {"pear", "Apple", "fig"};
        Arrays.sort(words);
        System.out.println(Arrays.toString(words));
    }
}
Output
[I@5e57643e
[42, 7, 19, 3, 25]
[3, 7, 19, 25, 42]
[9, 9, 9, 9]
[Apple, fig, pear]

Useful Arrays methods

These four cover most of what you need. Remember to import java dot util dot Arrays, at the top.

MethodDoes
Arrays.toString(a)[1, 2, 3]
Arrays.sort(a)sort in place
Arrays.fill(a, v)every box = v
Arrays.copyOf(a, n)a new copy, length n

Summary

Arrays dot to string prints an array, and sort sorts it. Import java dot util dot Arrays to use them. Next, searching an array.

Key takeaways
  • Arrays.toString
  • Arrays.sort
  • import java.util.Arrays
Next up: Searching an Array — is it there, and where?