Arrays in Java: How to Create and Use Them. Practical Tasks
Below are eight hands-on Java array exercises for beginners: from creating and initializing one-dimensional and two-dimensional arrays to finding max and min values, binary search, and a «garland» built on System.arraycopy(). We recommend studying the lessons of the Arrays section first. Every task has a full solution on Patreon.
One-Dimensional Array of Type String
- Create an array of type
Stringwith size 7. - Assign it the values of the days of the week.
- Print the value of the last element to the console.
Hint
Array indexing starts at zero, so in an array of 7 elements the last one has index 6. Instead of hard-coding the number, access the last element as days[days.length - 1] — this code will not break if the array size changes.
One-Dimensional Array of Type double
- Create an array of type
doublewith a size of 4. - Initialize it with any values using an initializer block.
- Print the value of the first element to the console.
Two-Dimensional Array of Type String
- Create a
Stringarray of size 3×6. - Initialize it with the following values:
a1 a2 a3 a4 a5 a6 b1 b2 b3 b4 b5 b6 c1 c2 c3 c4 c5 c6 - Print the array.
Good to know
You can print a two-dimensional array with two nested loops, or with a single line: System.out.println(Arrays.deepToString(array)). The Arrays.deepToString() method traverses nested arrays recursively — a plain Arrays.toString() on a 2D array would print only references to its rows.
Two-Dimensional Array of Type char
- Create a 2D array of type
charwith size 4×2. - Initialize it using an initializer block.
- Print the array values.
Max and Min Values in Each Row of a 2D Array
- Create a 5×8 integer array and initialize it using an initializer block.
- Find the maximum and minimum values in each row and store them in a 5×2 array.
- Print the new array containing the max and min values.
Easy to get wrong
Do not initialize max and min with zero: if every number in a row is negative, the maximum will get «stuck» at zero — a value that is not even in the array. Start with the first element of the row, array[i][0], and compare it with the rest.
Garland Simulation Using an Array
Implement the LED running light task (Java Operators Garland) using arrays: keep the state of each LED in an element of a boolean[] or int[] array. Use the System.arraycopy() method to simulate the scrolling effect.
Searching an Element with Arrays.binarySearch()
- Create a sorted
intarray of 10 elements, for example:{2, 5, 8, 12, 16, 23, 38, 45, 56, 72}. - Using the
Arrays.binarySearch()method, find the index of the element with the value 45. - Print the found index to the console. Then search for a value that is not in the array (for example, 100), print the result, and explain in a code comment what the negative number returned by the method means in this case.
Watch out
Arrays.binarySearch() works only on a sorted array — on an unsorted one the result is unpredictable. If the element is not found, the method returns a negative number equal to -(insertion point) - 1, not just -1: it tells you where the element would have to be inserted to keep the array sorted.
Copying Part of an Array with System.arraycopy()
- Create an
intarray of 10 elements and fill it with the values from 1 to 10. - Using the
System.arraycopy()method, copy the 3rd through 7th elements (indexes 2–6) into a new array of size 5. - Print both the original and the new array to the console using the
Arrays.toString()method.
Frequently Asked Questions
How do you declare and initialize an array in Java?
There are two main ways: with new and an explicit size — String[] days = new String[7]; (elements are filled with default values), or with an initializer block that supplies the values right away — double[] d = {1.5, 2.7, 3.1, 4.2};. For a two-dimensional array the blocks are nested: char[][] m = {{'a', 'b'}, {'c', 'd'}};.
How do you print an array to the console in Java?
Calling System.out.println(array) directly prints not the contents but a string like [Ljava.lang.String;@1b6d3586 — the type and hash. Use a for/for-each loop or the ready-made methods: Arrays.toString(array) for a one-dimensional array and Arrays.deepToString(array) for a two-dimensional one.
How do you find the maximum and minimum element of an array?
Declare max and min variables, initialize them with the first element of the array, and compare them with every following element in a loop: if (a[i] > max) max = a[i];. Since Java 8 the same can be done with the Stream API: Arrays.stream(a).max().getAsInt().
What does System.arraycopy() do and why is it better than a loop?
The method copies length elements from the src array, starting at position srcPos, into the dest array, starting at position destPos. It is a native JVM method — on large arrays it is noticeably faster than an element-by-element loop, and Arrays.copyOf() is built on top of it. When shifting elements (the running light), the source and the destination may be the same array.
What is a two-dimensional array in Java, really?
Java has no «matrix» type: a two-dimensional array is an array whose elements are themselves arrays. That is why array.length returns the number of rows, array[0].length returns the length of the first row, and rows may have different lengths (a jagged array).
Comments