First Steps in Java — Part 9

mike dietz
6 min readMay 6, 2020

--

Arrays

1: Setup | 2: Variables, Data Types and Sizes | 3: Get Some Input | 4: Operators | 5: Strings | 6: Conditionals | 7: Loops | 8: Methods | 9: Arrays

Photo by Vasily Koloda on Unsplash

We covered some ground in this beginner course First Steps in Java. We set up Java as a development environment and created our first .java files. We learned about data types, variables, strings, operators, methods, conditionals, and loops and created some small applications that take some user input and put it on the screen.
We conclude this course with the topic arrays. Create a file Arrays.java and code along as you go through this final section.

Hip, Hip, Array!

Java offers data containers of various kinds. We start today with the array.

Let’s gather some more information about what an array is:

  • An array is an object.
  • Members of an array are called array elements.
  • An array is a collection of elements with similar data types.
    Similar data types are the subtypes, i.e. the data types short and int are subtypes of long, and float is a subtype of double.
  • An array is indexed, i.e. each element is positioned. It can be accessed by referencing the index of the element. You reference the index of the element by adding square brackets with the index number.
  • The length of an array can be set at the time of creation, this cannot be changed later.
  • You can get the length of an array with the method length().
  • You can pass arrays as arguments to methods and return them back.
  • To be able to access the methods that the class Array offers, we need to import java.util.Arrays into our class. The Arrays class is part of the java.util package.

Open the file Arrays.java and put the import statement at the top of the file, before the class declaration.
import java.util.Arrays;

Now, that we have an idea of what an array is, we are going to create one.

Declare an Array

The declaration of an array must contain the datatype, the name, and the size. There are different ways to declare an array:

int[] myArray;
int []myArray;
int myArray[];

Instantiate an Array

Use the keyword new for an instantiation of an array. Provide the length of the array in square brackets.
int[] myArray = new int[5];

Initialize an Array

Now, it is time to fill our array with data.
You can declare, instantiate and initialize in one line, all at once:
int[] myArray = {1,2,3,4,5};

And you can also access and initialize an element individually with the index value:
myArray[0] = 1;

Or you can fill your array with a loop:
for (int i = 0; i < myArray.length; i++) {
myArray[i] = i + 1;
}

Here are some arrays of different data types:
Character Array
Use single quotes for characters.
char[] chArray = {'a', 'b', 'c'};
String Array
String[] strArray = {“Bob“, “Joe“, “Carl“, “Gil“};
Float Array
float[] floatArray = {1.2f, 4.1234f, 1.0f};

Let’s create an integer array and explore a few methods that the Array class provides.

Integer Array
int[] numberArray = {6,2,8,1,4,3};

Let’s print the array to the screen. If we use System.out.println(intArray), we get:
I@4cc451f2
An array is an object and since objects are reference types, we will get the address of the object and not the object itself. Java puts saves the address of the object in a hashCode table. The code we see has the format: classtype@hashCode

Output an Array
There are different ways to output an array.

Loop
Check the chapter on loops again if you are uncertain about how to create a loop.
for (int i = 0; i < numberArray.length — 1; i++) {
System.out.println(numberArray[i]);
}

toString()
This method is included in the Array class. We will use this method for the rest of the lesson.
System.out.println(Arrays.toString(numberArray));
output: [6, 2, 8, 1, 4, 3]

Now, that we can output our array, let’s explore some possibilities about what we can do with an array.

Sort an Array
The Array class offers the sort() method as a utility to sort an array. This works for numbers, as well as for strings.
Note: as useful these utility methods are, it is advisable to at least check how they work. This is not part of this short introduction but you should keep this in mind.
Arrays.sort(numberArray);
output: [1, 2, 3, 4, 6, 8]

Reverse the order
There are libraries that offer a reverse method but we will take the opportunity to write our own script.

  • To reverse the order in an array, we want to exchange the first element with the last one and the second element with the second last, etc.
    We use the index for this purpose. The last element, no matter how long the array is, is always at arrayName.length -1.
  • To exchange the first part of the array elements with the second part, we only loop through the first half of the array.
  • We need temporary storage for the element that is overwritten when doing the exchange, so we can fill the element, which value was taken to overwrite the first element, with the value of the temporary storage.
    For example, we have an array with the elements 1, 2, 3
    We put the value 1 into temporary storage. Then we take value three and overwrite value 1. And finally, we overwrite 3 with the temporary value 1.

The code:
for (int i = 0; i < numberArray.length/2; i++) {
int tempStorage = numberArray[i];
numberArray[i] = numberArray[numberArray.length -i -1];
numberArray[numberArray.length -i -1] = tempStorage;
}

Next, let’s create our own method to double the values of an integer array.

Double Values
We create a public, static method of dataype integer array inside the class but outside the main method. The method accepts an argument of type integer array.
public static int[] doubleValues(int[] arr){}
Inside the method body, we create a for loop that runs through the indices of the array element.
for (int i = 0; i < arr.length; i++) {}
Each element, we multiply by 2.
arr[i] = arr[i] * 2;

Here is the complete code:
public static int[] doubleValues(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
}
return null;
}

In the main method, we will now call the method doubleValues() on our array and assign it to a new variable of type integer array.
int[] doubledValues = doubleValues(numberArray);
And print it to the screen. System.out.println(Arrays.toString(numberArray));
output: [8, 6, 4, 3, 2, 1]

To practice what we just learned, create an array of type string, print it to the screen, and use the above method sort() and the script for reversing the order on the string array.

All the examples were illustrated on one-dimensional arrays. It’s time to look at the possibilities of multi-dimensional arrays.

Two-Dimensional Array

The two-dimensional array can be compared to a table with rows and columns.

The steps of declaration, instantiation, and initialization are the same as in a one-dimensional array. You just need to add a new dimension by adding additional square brackets.

Declare a Two-Dimensional Array
int [][] twoDimArray = new int[2][2];

Initialize a Two-Dimensional Array
twoDimArray[0][0] = 0;

That’s all we need to know to create a two-dimensional array. Let’s get started and create a two-dimensional array of type string that holds the first name, last name, and the age of two people.
String[][] personArray = { {“Bob”, “Miller”, “23”}, {“John”, “Hall”, “44”} };

Output a Two-Dimensional Array
For printing a two-dimensional array, we have to use the utility method deepToString().
System.out.println(Arrays.deepToString(personArray));
output: [[Bob, Miller, 23], [John, Hall, 44]]

This is just a short introduction to arrays but I think it gives a small glimpse of the possibilities that an array offers. There is much more to explore.

Get the code for this lesson at GitHub.

I hope you enjoyed this course and I wish you fun for your next steps in Java on your own. If you are wondering where to continue, in this lesson we talked about the array but there are more data collections that Java offers, e.g. the interfaces Collection, Set, Map and List, and their implementations HashList, HashSet, HashMap, and ArrayList.

--

--