Lesson 7 - Arrays in Java
In the previous exercise, Solved tasks for Java lesson 6, we've practiced our knowledge from previous lessons.
Lesson highlights
Are you looking for a quick reference on Java arrays instead of a thorough-full lesson? Here it is:
Shortened initialization of an array:
int[] numbers = {2, 3, 5, 7};
Writing 1
at the position [0]
:
numbers[0] = 1;
Reading the value (now 1
) at the position
[0]
:
{JAVA_CONSOLE}
int[] numbers = {2, 3, 5, 7};
numbers[0] = 1;
System.out.println(numbers[0]);
{/JAVA_CONSOLE}
Printing the whole array:
{JAVA_CONSOLE}
int[] numbers = {2, 3, 5, 7};
numbers[0] = 1;
for (int i : numbers) {
System.out.printf("%d ", i);
}
{/JAVA_CONSOLE}
Creating and empty array and generating the
values using a for
loop:
{JAVA_CONSOLE}
int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}
for (int i : numbers) {
System.out.printf("%d ", i);
}
{/JAVA_CONSOLE}
Sorting/searching using the
Array
class:
package onlineapp;
import java.util.Arrays;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
String[] simpsons = {"Homer", "Marge", "Bart", "Lisa", "Maggie"};
Arrays.sort(simpsons); // sort the array
System.out.printf("Bart is at the position: %s\n", Arrays.binarySearch(simpsons, "Bart")); // gets the item index
String[] copy = new String[5];
copy = Array.copyOfRange(simpsons, 0, 4); // copies 5 items to the "copy" array
for (String s : simpsons) {
System.out.printf("%s ", s);
}
}
}
Would you like to learn more? A complete lesson on this topic follows.
In the previous tutorial, Solved tasks for Java lesson 6, we sanitized the user input parts of our calculator in Java. In today's lesson, we're going to introduce you all to the array data structure and show you what it's capable of accomplishing.
Array
Imagine that you want to store some information about multiple items, e.g.
you want to keep 10 numbers in a memory, each of the fields of a checkerboard or
names of 50 users. Perhaps you realize that there must be an easier way than to
start typing variables like user1
, user2
... up until
user50
. Despite the fact that there may be 1000 of them. How would
go about searching for something in there? Definitely not like that!
If we need to store a larger amount of variables of the same
type, we can solve this problem using an array. We can imagine it as a
row of boxes, each of them containing one item. The boxes are numbered by
indexes, the first one has index 0
.
(We see an array of 8 numbers on this picture)
Programming languages are very different in the way they work with arrays. In some languages (especially the older ones, compiled), it wasn't possible to create an array with a size specified at runtime (e.g. to specify its size using some variable). Arrays had to be declared with a constant size in the source code. A workaround was made by inventing pointers and custom data structures, which often lead to errors in manual memory management and to program instability (e.g. in C++). On the other hand, some interpreted languages allow us to not only declare arrays of any size but to also change the size of an existing array (it's possible e.g. in PHP). We know that Java is a virtual machine, which is something between a compiled language and an interpreted language. Therefore, we are able to declare an array with a size which we can enter during the runtime, but once an array is created, its size can't be modified. Of course, we can work around it or use other data structures, but we'll get to that later.
You might be wondering why we're dealing with arrays when they evidently have some limitations and there are better data structures out there. The answer is: "Arrays are simple". I don't mean that they're easy for us to understand, which they are, but it's simple for Java. Working with arrays is fast since the items are simply stored in memory as a sequence (next to each other), and every item occupies the same amount of space and is quickly accessible. Many internal Java functions work with arrays somehow or return them. It is a key data structure.
We use loops for the mass handling of array items.
We declare an array using brackets:
int[] numbers;
Numbers
is obviously a name of our variable. Now, however, we've
just declared that the variable numbers
is an array of integers.
Now we have to initialize it so we could use it. We'll use the new
keyword which we won't explain for now. Let's just be glad knowing that that's
how it is because arrays are reference data types (can be understood as complex
types):
int[] numbers = new int[10];
Now we have an array of a size of ten int
s in the variable
numbers
.
The array items can be accessed through brackets. Let's store the number
1
in the first index (index 0
):
int[] numbers = new int[10]; numbers[0] = 1;
Filling arrays manually like this wouldn't be too effective. Let's use a loop
and fill an array with numbers from 1
to 10
. We'll use
a for
loop to do just that:
int[] numbers = new int[10]; numbers[0] = 1; for (int i = 0; i < 10; i++) { numbers[i] = i + 1; }
If we want to print this array, we need to add this piece of code after the one above:
{JAVA_CONSOLE}
int[] numbers = new int[10];
numbers[0] = 1;
for (int i = 0; i < 10; i++) {
numbers[i] = i + 1;
}
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
{/JAVA_CONSOLE}
Note that the array provides the length
constant, where its
length is stored, which is the number of its items. We can also use the
size()
method which returns the same thing.
Console application
1 2 3 4 5 6 7 8 9 10
We can also use a simplified version of the loop to work with collections, known as foreach. It iterates over the items in the array and detects the length of an array by itself. Its syntax is the following:
for (datatype variable : collection) { // commands }
The loop iterates over the items in the collection sequentially, from the first one to the last one. "Collection" is the general term for structures that contain multiple items, which in our case is an array. The current item is stored in the variable in each iteration of the loop.
Let's rewrite our existing program and use foreach. Foreach does not have a control variable, so it's not suitable for the creation of our array. We will primarily use it for printing.
{JAVA_CONSOLE}
int[] numbers = new int[10];
numbers[0] = 1;
for (int i = 0; i < 10; i++) {
numbers[i] = i + 1;
}
for (int i : numbers) {
System.out.print(i + " ");
}
{/JAVA_CONSOLE}
The output:
Console application
1 2 3 4 5 6 7 8 9 10
Of course, we can also fill an array manually, even without accessing each index gradually. We'll use curly brackets and separate items by commas:
String[] simpsons = {"Homer", "Marge", "Bart", "Lisa", "Maggie"};
Arrays are often used to store intermediate results, which are used later in the program. When we need some result 10 times, we won't calculate the same thing 10 times, instead, we'll calculate it once and put it into an array, then we just read the result.
The Arrays
class methods
Java provides the Arrays
class for us which contains helpful
methods for working with arrays.
In order to use them, we need to import the class first:
import java.util.Arrays;
Let's look at them:
Sort()
As the name suggests, the method will sort our array. Its only parameter is
the array that we want to sort. It is so clever that it works according to what
we have stored in the array. String
s are sorted alphabetically,
numbers are sorted depending on their value. Let's try to sort and print our
Simpsons family:
package onlineapp;
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
String[] simpsons = {"Homer", "Marge", "Bart", "Lisa", "Maggie"};
Arrays.sort(simpsons);
for (String s : simpsons) {
System.out.print(s + " ");
}
}
}
The output:
Console application
Bart Homer Lisa Maggie Marge
Try making an array of numbers and sort them, so you'll understand that it works for numerical datatypes as well.
BinarySearch()
Once we sort an array, Java allows us to search for items in it. The
binarySearch()
method returns the index of the first occurrence of
a value in the array. If it doesn't find the value, it returns -1
.
The method takes 2 parameters, the first is an array, the second is the item
we're searching for. Let's allow the user to enter the name of a Simpson's
character and tell them if it's really a Simpson. It won't be very useful for us
now since all we've got in our array are strings; however, it'll be very useful
for us when adding complex objects in the array. Just keep in mind that that's a
possibility until then. The array really has to be sorted first, then we
call the method!
package onlineapp;
import java.util.Arrays;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] simpsons = {"Homer", "Marge", "Bart", "Lisa", "Maggie"};
System.out.println("Hello! Enter the name of a character in the Simpsons (you may only choose from the core family members): ");
String simpson = scanner.nextLine();
Arrays.sort(simpsons);
int position = Arrays.binarySearch(simpsons, simpson);
if (position >= 0) {
System.out.println("Yes, it's a Simpson!");
}
else {
System.out.println("Hey! That's not a Simpson!");
}
}
}
Console application
Hello! What is your favorite character in the Simpsons (you may only choose from the core family members):
Homer
Yes, it's a Simpson!
CopyOfRange()
CopyOfRange()
, as the name suggests, copies a part of the array
into another array. The first parameter is the source array, the second is a
start position and the third is the end position. The method returns a new array
which is a slice of the original array.
A variable length of the array
We mentioned that the length of the array can be defined during run-time, let's try it out:
Scanner scanner = new Scanner(System.in); System.out.println("Hello, I'll calculate your grade average."); System.out.println("How many grades would you like to enter?"); int count = Integer.parseInt(scanner.nextLine()); int[] numbers = new int[count]; for (int i = 0; i < count; i++) { System.out.print("Enter grade number " + (i + 1) + ": "); numbers[i] = Integer.parseInt(scanner.nextLine()); } // computing the average int sum = 0; for (int i: numbers) { sum += i; } double average = sum / (double)numbers.length; System.out.println("Your grade average is: " + average);
Console application
Hello, I'll calculate your grade average.
How many grades would you like to enter?
5
Enter grade number 1: 1
Enter grade number 2: 2
Enter grade number 3: 2
Enter grade number 4: 3
Enter grade number 5: 5
Your grade average is: 2.6
This example could obviously be written without an array, but what if we wanted to compute the median, or print the given numbers backward? We wouldn't be able to do so without arrays. All of the original values are available in the array, which we can work with to do whatever we need to.
That's enough for today, you can play with arrays for a while if you'd like. In the next lesson, Solved tasks for Java lesson 7, I've got a surprise for you I think you might like
In the following exercise, Solved tasks for Java lesson 7, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 44x (64.05 kB)
Application includes source codes in language Java