Pages

Arrays in Java

Imagine cabinets in a storage room. Each of them has its own number, and each of them stores some Baggage object. Or a wine list where every kind of wine is numbered and you order by giving the number of your drink. Or a list of students in which "Adams" is recorded in the first position and "Zimmer" is last. Or a list of passengers on an airplane, each of whom is assigned a numbered seat. In Java, arrays are often used to work with such structures, i.e. sets of homogeneous data. Arrays in Java - 1
Arrays in the CodeGym course
On CodeGym, you start working with arrays on Level 7 of the Java Syntax quest. Three lessons are devoted to them, as well as 8 tasks on various levels to consolidate your skills working with arrays. But you'll encounter arrays many times during the course (in particular, the Array class will be studied in the Java Collections quest and as part of your future work.

What is an array?

An array is a data structure that stores elements of the same type. You can think of it as a set of numbered cells. You can put some data in each cell (one data element per cell). A specific cell is accessed using its number. An element's number in the array is also called an index. In Java, an array is homogeneous, i.e. all its cells contain elements of the same type. Thus, an array of integers contains only integers (int), an array of strings — only strings, and an array of instances of a Dog class that we've created will contain only Dog objects. In other words, Java won't let us put an integer in the first cell of the array, a String in the second, and a Dog in the third. Arrays in Java - 2

Declaring an array

How do you declare an array?

Like any variable, an array must be declared in Java. This can be done in one of two ways. They are equivalent, but the first way is more consistent with Java style. The second is a legacy of the C language: many C programmers switched to Java, and an alternate method was kept for their convenience. The table shows both ways of declaring an array in Java:
No.Declaring an array, Java syntaxExamplesComment
1.
dataType[] arrayName;
int[] myArray;

Object[]
arrayOfObjects;
It is advisable to declare an array this way. This is Java style.
2.
dataType arrayName[];
int myArray[];

Object
arrayOfObjects[];
Array declaration method inherited from C/C++, works in Java
In both cases, dataType is the type of the variables in the array. In the examples, we declared two arrays. One will store ints, and the other — Object objects. Thus, an array declration has a name and type (the type of the elements of the array). ArrayName is the name of the array.

Creating an array

How do you create an array?

Like any other object, you can create a Java array, i.e. reserve a place in memory for it, using the new operator. This is how it's done:
new typeOfArray[length];
where typeOfArray is the array's type and length is its length (i.e. the number of cells) expressed as a whole number (int). But note that here we only allocated memory for the array — we have not associated the declared array with any previously declared variable. Usually, an array is first declared and then instantiated, for example:
int[] myArray; // Array declaration
myArray = new int[10]; // Create (allocate memory for) an array of 10 ints
Here we created an array of integers called myArray, informing the compiler that it consists of 10 cells (each of which will contain an integer). However, it is much more common to use the following abbreviated syntax to create an array immediately when it is declared:
int[] myArray = new int [10]; // Declare the array and allocate memory "in one blow"
Please note: After an array is created using the new operator, its cells contain default values. For numeric types (as in our example), the default value is 0, for the boolean type, it is false, and for reference types, it is null. Thus, after executing this statement
int[] myArray = new int[10];
we get an array of ten integers and, until the program does something to change the values, each cell contains 0.
You can find more information about arrays in the article "Something about arrays"

Array length in Java

As we said above, the length of an array is the number of elements that the array is designed to hold. The length of an array cannot be changed after it is created. Please note that array elements are numbered starting from zero in Java. Thus, if we have an array of 10 elements, then the index of the first element is 0 and the index of the last is 9. Arrays in Java - 3You can get the array length using the length variable. For example:
int[] myArray = new int[10]; // Create an int array for 10 elements and name it myArray
System.out.println(myArray.length); // Display the array's length, i.e. the number of elements we can put into the array
Output: 10

Initializing an array and accessing its elements

Now we know how to create an array in Java. The process gets us not an empty array, but an array filled with default values. For example, for an int array, this is 0, and if we have an array of any reference type, then the default in each cell is null. We access an array element (for example, to set its value, display it on the screen, or perform some operation with it) by its index. Array initialization is the process of filling an array with specific values (other than the default). Example: let's create a string array for the 4 seasons and fill it with the names of the seasons.
String[] seasons = new String[4]; /* Declare and create an array. Java allocates memory for an array of 4 strings, and each cell is set to null (since String is a reference type) */

seasons[0] = "Winter"; /* We set the first cell, i.e. the cell with index zero, to "Winter". Here we access the zeroth element of the array and write a specific value to it. */
seasons[1] = "Spring"; // We follow a similar procedure for the cell with index 1 (the second cell)
seasons[2] = "Summer"; // ... index 2
seasons[3] = "Autumn"; // and finally, index 3
Now the names of the seasons are written to the four cells of our array. We could initialize the array in a different way, combining the declaration and initialization:
String[] seasons = new String[] {"Winter", "Spring", "Summer", "Autumn"};
What's more, the new operator can be omitted:
String[] seasons = {"Winter", "Spring", "Summer", "Autumn"};

How do you display an array on the screen in Java?

You can display array elements on the screen (i.e. on the console) using a for loop. Another, shorter way to display an array will be discussed in the paragraph entitled "Useful methods for working with arrays". In the meantime, take a look at this example where an array is displayed using a loop:
String[] seasons = new String {"Winter", "Spring", "Summer", "Autumn"};
for (int i = 0; i < 4; i++) {
System.out.println(seasons[i]);
}
The program will display the following: Winter Spring Summer Autumn

One-dimensional and multidimensional arrays in Java

But what if we want to create not an array of numbers, strings, or other objects, but rather an array of arrays? Java lets you do this. The sort of array we are already familiar with (int[] myArray = new int[8]) is known as a one-dimensional array. But an array of arrays is called a two-dimensional array. It's like a table that has a row number and a column number. Or, if you've learned the basics of linear algebra, you can think of it as a matrix. Arrays in Java - 4Why do we need such arrays? Well, to program matrices and tables, as well as other objects that have a similar structure. For example, a chessboard can be represented by an 8x8 array. A multidimensional array is declared and created as follows:
Int[][] myTwoDimentionalArray = new int[8][8];
This array has exactly 64 elements: myTwoDimentionalArray[0][0], myTwoDimentionalArray[0][1], myTwoDimentionalArray[1][0], myTwoDimentionalArray[1][1] and so on up to myTwoDimentionalArray[8][8]. So if we use it to represent a chessboard, then A1 corresponds to myTwoDimentionalArray[0][0] and E2 corresponds to myTwoDimentionalArray[4][1]. But how far can we push this? In Java, you can specify an array of arrays... an array of arrays of arrays, and so on. Of course, three-dimensional and higher-dimensional arrays are used very rarely. That said, you could use a three-dimensional array to program a Rubik's cube, for example.

Useful methods for working with arrays

Java has the java.util.Arrays class for working with arrays. In general, the most common operations performed on arrays are initialization (filling with elements), retrieving an element (by index), sorting, and searching. Searching and sorting arrays are topics for another day. On the one hand, it's good practice to write several search and sorting algorithms yourself. On the other hand, all the best algorithms have already been implemented and included in the standard Java libraries, and you can legally use them. Here are three useful methods in this class.

Sorting an array

The void sort(int[] myArray, int fromIndex, int toIndex) method sorts an integer array or subarray in ascending order.

Searching for an element in an array

int binarySearch(int[] myArray, int fromIndex, int toIndex, int key). This method looks for the key element in a sorted myArray array or subarray, from fromIndex to toIndex. If the item is found, then it returns its index. Otherwise, it returns (-fromIndex)-1.

Converting an array to a string

The String toString(int[] myArray) method converts to an array to a string. In Java, arrays don't override toString(). This means that if you try to display an entire array all at once (System.out.println(myArray)) rather than one element at a time as in the paragraph entitled "Display an array on the screen", you'll get the name of the class and the array's hexadecimal hash (defined by Object.toString()). If you're a beginner, you may not understand the explanation about the toString method. Initially, you don't need to, but using this method makes it easier to display an array. Java lets you easily display an array without using a loop. The example below demonstrates this.

An example using sort, binarySearch, and toString

Let's create an array of integers, display it using toString, sort it using the sort method, and then find some number in it.
class Main {
    public static void main(String[] args) {
        int[] array = {1, 5, 4, 3, 7}; // Declare and initialize the array
        System.out.println(array); // Try to display our array without using the toString method — the result is a hexadecimal number
        System.out.println(Arrays.toString(array)); // Display the array correctly
        Arrays.sort(array, 0, 4); // Sort the entire array from the zeroth to the fourth element
        System.out.println(Arrays.toString(array)); // Display the sorted array
        int key = Arrays.binarySearch(array, 5); // Look for the number 5 in the sorted array.
        // The binarySearch method will return the index of the array element we are searching for
        System.out.println(key); // Display the index of the number we searched for
System.out.println(Arrays.binarySearch(array, 0)); // Now try to find a number that isn't in the array,
        // and immediately display the result

    }
}
Output: [I@1540e19d [1, 5, 4, 3, 7] [1, 3, 4, 5, 7] 3 -1 The first string is an attempt to display the array without using toString. The second is the array displayed using toString. The third is the sorted array. The fourth is the index of the number we searched for (5) in the sorted array (remember that we count from zero, so the index of the array's fourth element is 3). In the fifth string, we see -1. This is an invalid array index. It signals that the number we searched for (in this case, 0) is not in the array.
More about methods in the Array class
Arrays class and its use — This article describes some methods in the Array class
The Arrays class has 18 important methods for working with arrays

Arrays in a nutshell

  • Essential characteristics of an array: the type of the data placed in it, its name, and its length.
    The last property is determined when the array is created (when memory is allocated for the array). The first two properties are determined when the array is declared.
  • The array size (number of cells) must be an int
  • It is impossible to change the length of an array after it is created.
  • An array element can be accessed by its index.
  • Elements in arrays, like everything else in Java, are numbered starting from zero.
  • After an array is created, it is filled with default values.
  • Arrays in Java are not the same as array in C++. They are almost like pointers to dynamic arrays.

Useful materials about arrays

Want to know more about arrays? Check out the articles below. There include a lot of interesting and useful material on this topic.
  1. Something about arrays — A good detailed article about arrays
  2. Arrays class and its use — This article describes some methods in the Array class

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.