Lesson 7 - Arrays in Java

Java Basic constructs Arrays in Java

In the previous tutorial, Loops in Java, 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.

Array structure in Java

(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 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. They made a workaround 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 ints 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 would be too laborious. 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:

for (int i = 0; i < numbers.length; i++) {
        System.out.print(numbers[i] + " ");
}

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.

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 + " ");
}

The output:

Console application
1 2 3 4 5 6 7 8 9 10

Of course, we can also fill our 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 a program. When we need some result 10x, we won't calculate the same thing 10x, instead, we'll calculate it once and put it into the 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. Strings are sorted alphabetically i.e. numbers depending on its value. Let's try to sort and print our Simpsons family:

String[] simpsons = {"Homer", "Marge", "Bart", "Lisa", "Maggie"};
Arrays.sort(simpsons);
for (String s : simpsons) {
        System.out.print(s + " ");
}

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 an item, they return -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!

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, Strings in Java - Working with single characters, I've got a surprise for you I think you might like ;-)


 

Download

Downloaded 36x (64.05 kB)
Application includes source codes in language Java

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
3 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
Previous article
Loops in Java
Thumbnail
All articles in this section
Java basic constructs
Activities (7)

 

 

Comments

Avatar
modi a jawo
Member
Avatar
modi a jawo:18. April 4:22

Hello, i want a much simplified explanation on loops and arrays. who can help me please?

 
Reply 18. April 4:22
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

1 messages from 1 displayed.