CodeGym /Java Course /New Java Syntax /Arrays class, part 2

Arrays class, part 2

New Java Syntax
Level 6 , Lesson 8
Available

"Rishi, I'm really looking forward to learning about the rest of the methods of the Arrays class.

"Such zeal for learning cannot but please your old teacher! But, if you really want to find out everything, a kind wizard named Google will help you day and night."

"Uh..."

"Just kidding. Kind of. Of course, I'll explain everything better, but if something comes up anything - remember the good wizard. I'll start today's lesson with the Arrays.fill method

"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 instead of all this, you can 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);

"Beautiful!"

"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 (or bad) 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.

6
Task
New Java Syntax, level 6, lesson 8
Locked
Filling an array
Implement a static main(String[]) method that populates the array variable with the values valueStart and valueEnd. If the length of the array is even, then its first half must be filled with valueStart values, and the second half with valueEnd. If the length of the array is odd, then fill the large

Arrays.copyOf()

"Amigo, please tell me how to change the size of an array after it has been created?"

"Umm... That's a trick question, right? I'm not that inexperienced anymore. The correct answer is that you can't! You cannot resize an array after it has been created."

"But what if you really want to?"

"It's still impossible!

"Actually, if you really want to, then you can! With the help of a programming trick:

  1. First, you create a new array of the desired length
  2. Then you copy all the elements from the first array into it.

"These are the two things that 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."

"What if the length of the new array is less than the length of the existing one?

"Great question, Amigo! If the elements don't fit, then the extra values are simply ignored."

"And if, on the contrary, there are extra cells, what are their initial values?

"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]"

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, you need another method of the Arrays class. It is Arrays.copyOfRange(). This is what calling it looks like:

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. Can you tell me whether the last element is included in this range?"

"Ha! As my great teacher used to say, 'in accordance with Java's good (or bad) old tradition, remember that the last element is not included in the range'."

"Amigo, you are growing right before our eyes.

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]"
6
Task
New Java Syntax, level 6, lesson 8
Locked
Splitting an array
Implement the main(String[]) method, which splits an array into two subarrays and fills a two-dimensional result array with them. If the length of the array is odd, then the larger half should be copied into the first subarray. Use the Arrays.copyOfRange(int[], int, int) method to split the array. D

Arrays.sort()

"And finally, I left the most... mmm... pleasant method for last: sorting. Arrays are sorted quite often in programming. Here are the top 3 most popular actions when working with arrays:

  • 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)

"Well-performing sorting algorithms, I must say, are not so easy to write. More precisely, this is a standard task, and as a student, it won't hurt you to practice writing sorting algorithms sometimes. But at work, it's better not to waste your time reinventing the wheel. 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! I called just one method and the array is sorted. A thing of beauty!"

"By the way, you can sort not only the entire array, but also 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. AND…

"I already know what you're going to say! 'In accordance with Java's good (or bad) 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 10,000 comparisons of array elements. Sorting an array of one million elements will involve about 20 million comparisons."

"Not too many comparisons when you consider the number of elements!"

"That's exactly what I'm saying. The QuickSort algorithm is very efficient.

6
Task
New Java Syntax, level 6, lesson 8
Locked
Sorting an array
Implement the main(String[]) method, which sorts array in ascending order. Use the Arrays.sort(int[]) method to sort the array.

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."

"Fantastic! We move straight to the goal very quickly!"

"Exactly. In an array of one million (!) elements, the binary search algorithm can find the index of the desired element in just 20 comparisons. The algorithm'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

"What if the desired element appears multiple times in the array?"

"That's a valid question, Amigo. In this case, the algorithm will 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)."

"What if the array doesn't contain the desired element at all?"

"In this case, the algorithm will return a negative index.

6
Task
New Java Syntax, level 6, lesson 8
Locked
Is anyone there?
Implement the main(String[]) method, which displays true if the element is contained in the passed array, otherwise false. The array variable should not change the position of its elements. To search for an element in an array, you need a binary search. To do this, use the static Arrays.binarySearc

Documentation

"Everything is clear, Rishi! This was very interesting."

"If you truly found this very interesting, then at your leisure skim through the official documentation of the Arrays class and its methods on the Oracle website.

"You can take a closer look at, for example, the Arrays.mismatch() and Arrays.compare() methods. You will most likely be able to put them to good use.

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

Comments (14)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
David Richard Level 17, Palestine
2 October 2024
Implement the main(String[]) method, which splits an array into two subarrays and fills a two-dimensional result array with them. If the length of the array is odd, then the larger half should be copied into the first subarray. Use the Arrays.copyOfRange(int[], int, int) method to split the array. Do not change the order of the elements. During testing, the values of the fields in the Solution class will be different. Take that into consideration. Can someone explain what is needed here?? Sometimes the coding parts are very easy, but the conditions confuse me (which is the most difficult part of the task) such as this task.... like we have two static arrays declared allready, one is two deminsional [2][] The other is one deminsional with it's values already inisialized...!!! What i want to know is "what is needed" so I can code it
nealgoogs Level 21, Eliot, United States
21 August 2024
Wrote my first ever ternary operator in the last coding exercise. Very cool.
Naif Al-Jaaidi Level 9, Aden, Yemen
22 December 2023
Imagine the array as a line of friends waiting for ice cream. Each friend has a number based on their position in line. Zero-based indexing: Everyone counts their position starting from 0, not 1. So, the first friend is #0, the second is #1, and so on. Array length: The length of the line is like the number of friends waiting. But instead of counting until the last friend, we stop one number before. So, a line of 5 friends only has indices from 0 to 3 (4 total numbers). Arrays.sort range: If the ice cream truck only wants to sort a part of the line, they can say "Sort everyone from number 1 (second friend) up to but not including number 4 (last friend)". That way, the first friend and the last friend stay still while the others get rearranged in order. Remember, in Java, we always count things from 0, and for Arrays.sort, we don't include the last number in the range we want to sort. Just think of it as skipping the last person in line for the sorting dance!
Kiran Nyayapati Level 47, Hyderabad, India
3 March 2022
@ CodeGym Team - Under Arrays.binarySearch() Examples line number 7, the negative index should be -1 instead of -7. Hope this is corrected.
Lisa L Level 47, Nuremberg, Germany
21 March 2022
no, the -7 is correct. Have a look at the java docs the retVal of binarySearch is (-(insertion point) - 1) where insertion point is the index the searched value would be sorted in here you look for 5 in -20, -20, -20, -2, 0, 3, 8, 11, 99, 999... means the 5 would take the place of the 8. The 8 is index 6 --> -6 - 1 = -7
steven anthony kwong Level 9, United Kingdom, United Kingdom
8 February 2022
I'm shocked to learn the last parameter in Arrays.copyOfRange can use a non-existent Indice of an array. Of course, I am aware that the "last" parameter is exclusive but this type of inconsistency is error-prone and extremely confusing to beginners like me. Now I see why some say some bad tradition is involved. I should not have to resort to using tricks to work around this. Shocking.
Hoa Nguyen Level 15, Australia Expert
14 January 2022
What is the difference between the two following command codes? I was marked as fail to complete the last task because I used: int[] copy = array; instead of int[] copy = Arrays.copyOf(array, array.length); Your advice is much appreciated.
Travis McKinstry Level 9, United States of America, United States
20 January 2022
Yeah, I've the same question. I tried creating an array using

int[] newArray = array;
And it didn't work. I also tried iterating over the original array, pushing each element to the new array, and that didn't work either. Seems like there are some other stipulations in this challenge that the creator didn't mention.
Jonaskinny Level 25, Redondo Beach, United States
4 February 2022
int[] copy = array --> copy points to the same memory address as array ... aka reference copy int[] copy = Arrays.copyOf(array,~) --> copy has been created and populated with values from array ... aka value copy
P.B.Kalyan Krishna Level 24, Guntur, India
23 February 2022
When you say int[] copy = array, you are assigning the reference contained in array variable to copy. Now both array and copy refer to the same array. Any changes made through copy will effect the original array referenced by array because the references are the same. But when you create a new array referenced by copy variable using the copyOf() in the Arrays class, you get a new independent array which is independent of the original array. Now if you sort the new array, the change is not effected to the original array. Now we have two identical arrays which are independent to each other and their references are different. It is given in the requirements that the position of elements in the original array should not be effected and should remain the same. We achieved this by creating a copy of the array and making changes to that copy instead of the original array. The original array remained the same.
Jcode Level 27, United Kingdom
10 January 2022
It seems Arrays.fill is implemented in a strange way. for example. public static int[] array = new int[20]; // creates an array of 20 elements with indices that start 0 end 19 // I would have expected to have entered Arrays.fill(array, 0,19, 55); // to populate all the elements of the array with 55. Pretty logical🙂 // instead, it requires Arrays.fill(array, 0,20, 55); // this just seems to add confusion it looks like we are starting at 0 ending at 20 making 21 elements
Jcode Level 27, United Kingdom
11 January 2022
At the risk of replying to my own question😊. CodeGym does mention the reason. that it's a java convention! CodeGym says, "I already know what you're going to say! 'In accordance with Java's good (or bad) old tradition, remember that the last element is not included in the range'.
Lisa L Level 47, Nuremberg, Germany
21 March 2022
That's pretty OK this way cause you can do smth like that:

Arrays.fill(array, 0, array,length, 55);
Michael Amann Level 22, United States of America, United States
5 April 2022
Yeah, someone didn't read the materials preceding the exercise. I guess they're there for a reason?🤔