CodeGym /Java Course /Module 1. Java Syntax /Arrays class, part 2

Arrays class, part 2

Module 1. Java Syntax
Level 11 , Lesson 5
Available

1. Arrays.fill()

When working with arrays, Java programmers very often need to fill the array with the same value. You can, of course, write a loop and simply assign some value to each cell of the array in the loop:

int[] x = new int[100];
for (int i = 0; i < x.length; i++)
x[i] = 999;

Or you can simply call the Arrays.fill() method, which does exactly the same thing: it fills the passed array with the passed value. Here's how it looks:

Arrays.fill(name, value)

And the code in the example above can be made a little bit more compact and clearer:

int[] x = new int[100];
Arrays.fill(x, 999);

You can also use the Arrays.fill() method to fill not the entire array, but a part of it, with some value:

Arrays.fill(name, first, last, value)

Where first and last are the indices of the first and last cells to be filled.

In accordance with Java's good old tradition, remember that the last element is not included in the range.

Example:

int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Arrays.fill(x, 3, 7, 999);


String str = Arrays.toString(x);


We're filling the cells x[3], x[4], x[5], and x[6] with the value 999. Cells of an array are numbered starting from zero!

The str variable contains the value:
"[1, 2, 3, 999, 999, 999, 999, 8, 9, 10]"

The Arrays.fill() method only works with one-dimensional arrays. If you pass a two-dimensional array to the method, it will be treated as one-dimensional, with all the ensuing consequences.


11
Task
New Java Syntax, level 11, lesson 5
Locked
Period and comma
Periods and commas are important for more than just punctuation in ordinary text. Fix mistakes in the code, so that the program compiles and works correctly.

2. Arrays.copyOf()

As you already know, you cannot resize an array after it has been created.

But what if you really want to?

Well, if you really want to, then you can!

  • Create a new array of the desired length
  • Copy all the elements from the first array into it.

By the way, this is exactly what the Arrays.copyOf() method does. This is what calling it looks like:

Type[] name2 = Arrays.copyOf(name, length);

This method does not change the existing array, but instead creates a new array and copies the elements of the old array into it.

If the elements don't fit (the length is less than the length of the existing array), then the extra values are ignored.

If the length of the new array is greater than the length of the old one, the cells are filled with zeros.

Example:

int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int[] x2 = Arrays.copyOf(x, 5);
String str2 = Arrays.toString(x2);

int[] x3 = Arrays.copyOf(x, 15);
String str3 = Arrays.toString(x3);


The str2 variable contains the value:
"[1, 2, 3, 4, 5]"

The str3 variable contains the value:
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0]"

3. Arrays.copyOfRange()

And what if you want to get an array of length 5 from an array of length 10, but you need it to contain the last 5 elements rather than the first 5?

In this case, another method of the Arrays class will come in handy — the Arrays.copyOfRange(). Here's what it looks like when we call it:

Type[] name2 = Arrays.copyOfRange(name, first, last);

This method also creates a new array, but fills it with elements from an arbitrary place in the original array. Where first and last are the indices of the first and last elements that should be put into the new array.

In accordance with Java's good old tradition, remember that the last element is not included in the range.

Example:

int[] x = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};

int[] x2 = Arrays.copyOfRange(x, 5, 10);
String str2 = Arrays.toString(x2);

int[] x3 = Arrays.copyOfRange(x, 5, 15);
String str3 = Arrays.toString(x3);


The str2 variable contains the value:
"[16, 17, 18, 19, 20]"

The str3 variable contains the value:
"[16, 17, 18, 19, 20, 0, 0, 0, 0, 0]"

11
Task
New Java Syntax, level 11, lesson 5
Locked
Oh, these damnable quotation marks
The code already has quotation marks, but as it turns out, there are not enough of them. Fix mistakes in the code, so that the program compiles and works correctly.

4. Arrays.sort()

Ah, the most delicious treat: sorting. Arrays are sorted quite often in programming. The three most common actions when working with arrays are:

  • Sorting an array
  • Finding the minimum (or maximum) element of an array
  • Determining the index of an element in an array (finding an element in an array)

This is precisely why Java's creators included the sort() method in the Arrays class. This is what calling it looks like:

Arrays.sort(name);

This method sorts the passed array in ascending order.

Example:

int[] x = {11, -2, 3, 0, 999, -20, 8, -20, 99, -20};

Arrays.sort(x);

String str = Arrays.toString(x);



The str variable contains the value:
"[-20, -20, -20, -2, 0, 3, 8, 11, 99, 999]"

Excellent, right? You called one method, and now you have a sorted array. Beautiful.

By the way, you can use this method to sort not only the entire array, but just part of it. This is what calling it looks like:

Arrays.sort(name, first, last);

Where first and last are the indices of the first and last cells that the sort should touch.

In accordance with Java's good old tradition, remember that the last element is not included in the range.

Example:

int[] x = {11, -2, 3, 0, 999, -20, 8, -20, 99, -20};

Arrays.sort(x, 4, 8);
String str = Arrays.toString(x);


The str variable contains the value:
"[11, -2, 3, 0, -20, -20, 8, 999, 99, -20]"

To sort arrays, Java uses the fastest sorting algorithm — QuickSort. Its computational complexity depends on the size of the array and is calculated using the formula N log(N).

Sorting an array of 1000 elements will involve about 3,000 comparisons of array elements. Sorting an array of one million elements will involve about 6 million comparisons.


11
Task
New Java Syntax, level 11, lesson 5
Locked
Con, Cat, Enation
"Con", "cat", "enation". How would you merge these three strings? Do you remember how to concatenate Strings in Java? Fix mistakes in the code, so that the program compiles and works correctly.

5. Arrays.binarySearch()

Well, and the last of the most interesting methods of the Arrays class is able to search for a given value in an array. This is no ordinary search — it is the beloved binary search. It boils down to this:

  • First, the array is sorted.
  • Then the middle element of the array is compared with the one we are looking for.
  • If the element is greater than the middle element, then the search continues in the right half of the array.
  • If the element we are looking for is less than the middle element, then the search continues in the left half of the array.

Because the array is sorted, it is possible to eliminate half of it in a single comparison. Then in the next step, we toss out another half, and so on.

This approach makes binary search very fast. In an array of one million (!) elements, it can find the index of the desired element in just 20 comparisons. The approach's shortcoming is that the array must first be sorted, and sorting also takes time.

This is what calling it looks like:

int index = Arrays.binarySearch(name, value);

Where name is the name of the array, which must be passed already sorted (for example, using the Arrays.sort() method). And value is the element we are searching for in the array. The result returned by the method is the index of the desired array element.

Examples:

int[] x = {11, -2, 3, 0, 999, -20, 8, -20, 99, -20};
Arrays.sort(x);

int index1 = Arrays.binarySearch(x, 0);
int index2 = Arrays.binarySearch(x, -20);
int index3 = Arrays.binarySearch(x, 99);
int index4 = Arrays.binarySearch(x, 5);
x is:
{-20, -20, -20, -2, 0, 3, 8, 11, 99, 999}

4
1 (indices 0 and 2 are also acceptable)
8
-7

If the array contains multiple instances of the element being searched for, then the algorithm will simply return the index of one of them (there is no guarantee that it will be, say, the very first, or vice versa — the very last of these duplicate elements)."

If the element is not found in the array, then the index will be negative.


11
Task
New Java Syntax, level 11, lesson 5
Locked
Keeping track of parentheses
It seems we have an extra parenthesis? Or is one missing? Deal with the problem.

6. Link to Oracle documentation on the Arrays class

If you are super interested, you can read everything about the Arrays class and all its methods in the official documentation on the Oracle website.

For example, you can read about the Arrays.mismatch() and Arrays.compare() methods. Maybe you will find them useful somehow.

And don't be confused by the number of methods. Each method has 5-10 variants, which differ only in their parameter types.


11
Task
New Java Syntax, level 11, lesson 5
Locked
And parentheses once again
It seems that once again the problem is with the parentheses. But with different ones this time. Fix mistakes in the code, so that the program compiles and works correctly.
11
Task
New Java Syntax, level 11, lesson 5
Locked
The long-suffering main method
Make one fix in the code to get the program to run.
11
Task
New Java Syntax, level 11, lesson 5
Locked
Correct class
Fix mistakes in the code, so that the program compiles and works correctly.
11
Task
New Java Syntax, level 11, lesson 5
Locked
Need a package?
Fix a mistake in the code, so that the program compiles and works correctly.
11
Task
New Java Syntax, level 11, lesson 5
Locked
Imported code
Fix a mistake in the code, so that the program compiles and works correctly.
Comments (5)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
12 December 2023
my code of "Filling an array" with loops was 10 characters shorter to me than with usage of "fill", but probably useful in the future to know this... "Is anyone there?" I did it in a 1 liner, but validation failed on "true" and it didn't turned out why, why we had to use the copy and sort when it's not in reqs... confusing
Anonymous #11420114 Level 8, Bogota, Colombia
2 December 2023
Very good comment on the boolean variable use for sysprint
Parsa Level 62, Bangalore, India Expert
10 November 2023
Arrays.fill can work with multidimensional arrays too, you just have to specify the dimension. Consider this:

int[][] x = { {1,2,3}, {4,5,6}, {7,8,9} };

Arrays.fill(x[0],10);

System.out.println(Arrays.deepToString(x));
The output: [[10, 10, 10], [4, 5, 6], [7, 8, 9]] Arrays.fill(x[1],10) will result in: [[1, 2, 3], [10, 10, 10], [7, 8, 9]]
Josip Batinić Level 17, Croatia
3 February 2023

boolean found = index >= 0; 
Could be used for checking if the number is in array. This line of code is used to determine whether the given element is present in the array. The Arrays.binarySearch() method returns the index of the element if it is present in the array. If the element is not present, it returns a negative number. Therefore, the code found = index >= 0; is used to check if the element is present and set the boolean variable found accordingly. Use

Arrays.copyOf(array, array.length);
Insted of:

Arrays.copyOfRange(array, 0, array.length);
For some reason copyOfRange does not work. You need to copy original array, because you cannot change the value of it.
GioGTelian Level 10
7 November 2022
awesome lesson!