Summary - Array methods
- Java course
- Beginner
- Lesson 64/116
- 5 min
Combine sort, binarySearch and toString to write a sorting tool.
Summary: Array methods
In this group you met five important Arrays methods that work on arrays: sort, toString, binarySearch, copyOf and fill.
They all live in java.util.Arrays. sort and fill modify the array in place; toString and copyOf return new values. binarySearch requires a sorted array.
By combining these methods you can build sort + search + print tools. Now you will write a small sorting tool.
Practice Sorted list tool
Sort the given scores, print them on one line using Arrays.toString, then look up 72 with Arrays.binarySearch and print the found index.
Starter code
public class Main {
public static void main(String[] args) {
int[] scores = {88, 72, 55, 90, 64};
// Sort the array
// Print the array on one line
// Search for 72 and print the index
}
}Sample solution
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));
int i = Arrays.binarySearch(scores, 72);
System.out.println(i);Expected output
[55, 64, 72, 88, 90] 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method does not work on an unsorted array?
- Arrays.sort Correct answer
- Arrays.binarySearch
- Arrays.toString
- Arrays.fill
Explanation: binarySearch requires a sorted array; the others do not.
2 Fill in the blank: array text
int[] nums = {2, 1, 3};
String text = ____.toString(nums);
int[] nums = {2, 1, 3};
String text = Arrays.toString(nums);
Explanation: Arrays.toString(nums) produces the text.
3 Match method to return type
| Term | Meaning |
|---|---|
Arrays.sort(x) |
void |
Arrays.toString(x) |
String |
Arrays.binarySearch(x, v) |
int |
Arrays.copyOf(x, n) |
int[] |