Lesson 6 of 10

Arrays

Goal

The length field, Arrays.sort and Arrays.toString

01

Explanation

An array is a fixed-length group of values of one type, like int[] scores = {70, 95, 81};, or new int[5], which creates five slots that each hold zero. You read an element by its index, and counting starts at zero: the first element is scores[0] and the last is scores[scores.length - 1]. Here length is a field, written without parentheses, and if you ask for a position outside the bounds, the program throws an ArrayIndexOutOfBoundsException.

The Arrays class in java.util holds handy tools for arrays: Arrays.sort(a) sorts the array in ascending order, Arrays.toString(a) turns the array into readable text like [60, 70, 81], and Arrays.copyOf(a, n) copies its first n elements into a new array, while a.clone() copies the whole thing.

Watch out for two things. First, printing an array directly shows something like [I@1b6d3586 instead of its elements. Second, Arrays.sort sorts the array itself and returns nothing. A variable doesn't hold an array, it points to one, so a method that receives an array works on the original, and whatever it sorts inside is changed for the caller too. That's why you copy it first when you want the original to stay as it is.

02

Your task

Write average(a) to return the average as a decimal, or 0 for an empty array. Write reversed(a) to return a new array in reverse order, and top3(scores) to return the three highest scores sorted from highest to lowest, or all the scores if there are fewer than three. None of these methods may change the original array. Then print the result of top3(scores) from main in the form [95, 88, 81].

Checks

6 checks
  1. average returns a decimal average, not an integer
  2. average returns 0 for an empty array, not NaN
  3. reversed returns the array in reverse order
  4. reversed returns a new array and leaves the original alone
  5. top3 returns the three highest scores from highest down and leaves the original alone
  6. [95, 88, 81] was printed
03

Hints

0/3
Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.

Main.java
OutputJava 13 (Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.