JavaRush /Java Blog /Random EN /Arrays in Java

Arrays in Java

Published in the Random EN group
Imagine cells in a storage room. Each has its own number, and each contains some kind of “Luggage” object. Or a wine list, in which all types of wine are numbered and when you place an order, you just need to give the number of the drink. Or a list of students in a group, in which student “Andreev” will be written in the first cell, and “Yakovlev” in the last cell. Or a list of airplane passengers, each of whom is assigned a seat with a specific number. In Java, to work with similar structures, that is, a lot of homogeneous data, arrays in Java are often used.

What is an array?

An array is a data structure that stores elements of the same type. It can be thought of as a set of numbered cells, each of which can contain some data (one data element per cell). Access to a specific cell is carried out through its number. The number of an element in an array is also called the index . In the case of Java, the array is homogeneous, that is, all its cells will store elements of the same type. So, an array of integers contains only integers (for example, of type int ), an array of strings contains only strings, an array of elements of the Dog class we created will contain only Dog objects . That is, in Java, we cannot put an integer in the first cell of an array, a String in the second , and a “dog” in the third. Arrays in Java

Array Declaration

How to declare an array?

Like any variable, an array in Java must be declared. You can do this in one of two ways. They are equivalent, but the first one is more consistent with the Java style. The second is the legacy of the C language (many C programmers switched to Java, and for their convenience an alternative method was left). The table shows both ways to declare an array in Java:
No. Array declaration, Java syntax Examples A comment
1.
dataType[] arrayName;
int[] myArray;

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

Object
arrayOfObjects[];
An inherited way of declaring arrays from C/C++ that also 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 integers of type int , the other will store objects of type Object . Thus, when an array is declared, it has a name and a type (the type of array variables). arrayName is the name of the array.

Creating an Array

How to create an array?

Like any other object, you can create a Java array, that is, reserve memory space for it, using the new operator . This is done like this:
new typeOfArray [length];
Where typeOfArray is the type of the array, and length is its length (that is, the number of cells), expressed in integers ( int ). However, here we have only allocated memory for the array, but have not associated the created array with any previously declared variable. Usually an array is first declared and then created, for example:
int[] myArray; // array declaration
myArray = new int[10]; // creation, that is, allocation of memory for an array of 10 elements of type int
Here we declared an array of integers called myArray , and then declared that it consists of 10 cells (each of which will store an integer). However, it is much more common to create an array immediately after the declaration using this shorthand syntax:
int[] myArray = new int[10]; // declaration and allocation of memory "in one bottle"
Note:After creating an array using new , its cells are filled with default values. For numeric types (as in our example) this will be 0, for boolean - false , for reference types - null . Thus, after the operation
int[] myArray = new int[10];
we get an array of ten integers, and until this changes during the program, each cell contains a 0.

More information about arrays can be found in the article “ Something about arrays

Array length in Java

As we said above, the length of an array is the number of elements for which the array is designed. The length of an array cannot be changed once it is created. Note:In Java, array elements are numbered starting from zero. That is, if we have an array of 10 elements, then the first element of the array will have index 0, and the last one will have index 9. Arrays in Java - 3You can access the length of the array using the length variable . Example:
int[] myArray = new int[10]; // created an array of integers with 10 elements and named it myArray
System.out.println(myArray.length); // printed to the console the length of the array, that is, the number of elements that we can put in the array
Program output:
10

Initializing an array and accessing its elements

How to create an array in Java is already clear. After this procedure, we do not get an empty array, but an array filled with default values. For example, in the case of int these will be 0, and if we have an array with data of a reference type, then by default, null is written in each cell . We access an array element (that is, we write a value into it or display it on the screen or perform some operation with it) by its index. Initializing an array is filling it with specific data (not by default). Example: let's create an array of 4 seasons and fill it with string values ​​- the names of these seasons.
String[] seasons  = new String[4]; /* declared and created an array. Java allocated memory for an array of 4 strings, and now each cell is null (because the string is a reference type)*/

seasons[0] = "Winter"; /* in the first cell, that is, in the cell with a zero number, we wrote the string Winter. Here we get access to the zero element of the array and write a specific value there */
seasons[1] = "Spring"; // do the same procedure with cell number 1 (second)
seasons[2] = "Summer"; // ...number 2
seasons[3] = "Autumn"; // and with the last one, number 3
Now all four cells of our array contain the names of the seasons. Initialization can also be done differently, combining initialization and declaration:
String[] seasons  = new String[] {"Winter", "Spring", "Summer", "Autumn"};
Moreover, the new operator can be omitted:
String[] seasons  = {"Winter", "Spring", "Summer", "Autumn"};

How to display an array in Java on the screen?

You can display array elements on the screen (that is, to the console), for example, using a for loop . Another, shorter way to display an array on the screen will be discussed in the paragraph “Useful methods for working with arrays” below. For now, let’s look at an example with cyclic output of an array:
String[] seasons  = new String[] {"Winter", "Spring", "Summer", "Autumn"};
for (int i = 0; i < 4; i++) {
System.out.println(seasons[i]);
}
As a result, the program will output the following result:
Winter Spring Summer Autumn

One-dimensional and multidimensional Java arrays

What if we want to create not an array of numbers, an array of strings, or an array of some objects, but an array of arrays? Java allows you to do this. The already familiar array int[] myArray = new int[8] is a so-called one-dimensional array. And an array of arrays is called two-dimensional. It is like a table that has a row number and a column number. Or, if you learned the beginnings of linear algebra, on a matrix. Arrays in Java - 4Why are such arrays needed? In particular, for programming the same matrices and tables, as well as objects that resemble them in structure. For example, the playing field for chess can be specified as an 8x8 array. A multidimensional array is declared and created as follows:
int[][] myTwoDimentionalArray = new int [8][8];
There are exactly 64 elements in this array: myTwoDimentionalArray[0][0], myTwoDimentionalArray[0][1], myTwoDimentionalArray[1][0], myTwoDimentionalArray[1][1]and so on up to myTwoDimentionalArray[7][7]. So if we use it to represent a chessboard, then cell A1 will represent myTwoDimentionalArray[0][0], and E2 will represent myTwoDimentionalArray[4][1]. Where there are two, there are three. In Java, you can specify an array of arrays... an array of arrays of arrays, and so on. True, three-dimensional and more arrays are used very rarely. However, using a three-dimensional array, you can program, for example, a Rubik's cube.

What else to read

Multidimensional arrays

Useful methods for working with arrays

To work with arrays in Java there is a class java.util.Arrays (arrays in English means “arrays”). In general, the following operations are most often performed with arrays: filling with elements (initialization), retrieving an element (by number), sorting and searching. Searching and sorting arrays is a separate topic. On the one hand, it is very useful to practice and write several search and sorting algorithms yourself. On the other hand, all the best practices have already been written and included in the Java libraries, and can be legally used. Here are three useful methods of this class

Sort an array

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

Searching an array for the desired element

int binarySearch(int[] myArray, int fromIndex, int toIndex, int key). This method searches for the key element in an already sorted myArray or subarray, starting from fromIndex and ending to toIndex . If the element is found, the method returns its index, if not - (-fromIndex)-1.

Converting an array to a string

The method String toString(int[] myArray)converts the array to a string. The thing is that in Java arrays do not override toString() . This means that if you try to display the entire array (rather than element by element, as in “ Printing an Array to the Screen ”) to the screen directly ( System.out.println(myArray)), you will get the class name and the hexadecimal hash code of the array (this is defined by Object.toString() ). If you are a beginner, you may not understand the explanation of the method toString. At the first stage this is not necessary, but using this method the output of the array is simplified. Java makes it easy to display an array without using a loop. More on this in the example below.

Example on sort, binarySearch and toString

Let's create an array of integers, display it on the screen using toString , sort it using the sort method , and find some number in it.
class Main {
    public static void main(String[] args) {
        int[] array = {1, 5, 4, 3, 7}; //declaring and initializing the array
        System.out.println(array);//trying to display our array on the screen without the toString method - we get a hexadecimal number
        System.out.println(Arrays.toString(array));//печатаем массив "правильно"
        Arrays.sort(array, 0, 4); // sort the entire array from zero to the fourth member
        System.out.println(Arrays.toString(array));//print the sorted array to the screen
        int key = Arrays.binarySearch(array, 5); // ищем key - число 5 в отсортированном массиве.
        //binarySearch method will return the index of the sorted array element, in which the required number is "hidden"
        System.out.println(key);//распечатываем индекс искомого числа
System.out.println(Arrays.binarySearch(array, 0));//а теперь попробуем найти число, которого в массиве нет,
        // and immediately display the result on the screen

    }
}
Program output:
[I@1540e19d [1, 5, 4, 3, 7] [1, 3, 4, 5, 7] 3 -1
The first line is an attempt to display an array without toString , the second is displaying an array using toString , the third is a sorted array, the fourth is the index of the desired number 5 in a sorted array (remember that we are counting from zero, so the fourth element of the array has an index 3). In the fifth line we see the value -1 . An array does not have such an index. The output signals that the desired element (in this case, 0) is not in the array.

More about Array class methods

The Arrays class and its use - the article describes some methods of the Array class

The main thing about arrays

  • The main characteristics of an array: the type of data placed in it, name and length.
    The latter is decided during initialization (allocating memory for the array), the first two parameters are determined when declaring the array.

  • The array size (number of cells) must be defined in int

  • You cannot change the length of an array after it has been created.

  • An array element can be accessed by its index.

  • In arrays, as elsewhere in Java, elements are numbered starting from zero.

  • After the array creation procedure, it is filled with default values.

  • Arrays in Java are structured differently than in C++. They are almost the same as pointers to dynamic arrays.

Useful materials about arrays

Want to know more about arrays? Please take a look at the articles below. There is a lot of interesting and useful information on this topic.
  1. Something About Arrays - Good detailed article on arrays

  2. The Arrays class and its use - the article describes some methods of the Array class

  3. Multidimensional arrays - a detailed article about multidimensional arrays with examples.

  4. Return a zero-length array, not null - Effective Programming author Joshua Bloch talks about how to better return empty arrays

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION