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 “Baggage” object. Or a wine list, in which all types of wine are numbered and when you place an order, you just need to name the number of the drink. Or a list of students in the group, in which the first cell will contain the student "Andreev", and the last cell - "Yakovlev". Or a list of aircraft passengers, each of which 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 represented as a set of numbered cells, each of which can contain some data (one data element per cell). Access to a particular cell is carried out through its number. The number of an element in an array is also called an index . In the case of Java, an 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 the array, and a String in the second, and in the third - "dog". 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 equal, but the first one is more in line with the Java style. The second is the legacy of the C language (many C programmers switched to Java, and an alternative method was left for their convenience). The table shows both ways of declaring an array in Java:
No. Array declaration, Java syntax Examples A comment
dataType[] arrayName;
int[] myArray;

It is desirable to declare an array in this way, this is Java-style
dataType arrayName[];
int myArray[];

A C/C++ way of declaring arrays that works in Java as well
In both cases, dataType is the type of the variables in the array. In the examples, we have 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 . It 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 only allocated memory for the array, but did not associate 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 named myArray , and then said that it consists of 10 cells (each of which will store some 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 with new , its cells are stored with default values. For numeric types (as in our example) this will be 0, for boolean it will be false , for reference types it will be null . So after surgery
int[] myArray = new int[10];
we get an array of ten integers, and until this changes during the course of the program, 0 is written in each cell.

More information about arrays is 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 calculated. The length of an array cannot be changed after it has been created. Note:in Java, array elements are numbered from zero. That is, if we have an array of 10 elements, then the first element of the array will have an index of 0, and the last one will Arrays in Java - 3have an index of 9. You 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:

Array initialization and access to its elements

How to create an array in Java is already clear. After this procedure, we get not an empty array, but an array filled with default values. For example, in the case of int, it 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, write a value to 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 in a different way, combined with 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?

You can print the elements of an array to the screen (that is, to the console), for example, using the for loop . Another, shorter way to display an array on the screen will be discussed in the “Useful Techniques for Working with Arrays” section below. In the meantime, consider an example with an array loop:
String[] seasons  = new String[] {"Winter", "Spring", "Summer", "Autumn"};
for (int i = 0; i < 4; i++) {
As a result, the program will display the following result:
Winter Spring Summer Autumn

One-Dimensional and Multi-Dimensional Java Arrays

But 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 the 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 studied the beginning of linear algebra, - to the matrix. Arrays in Java - 4What are these arrays for? 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 with an 8x8 array. A multidimensional array is declared and created like this:
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[7][7]. So if we use it to represent a chessboard, then cell A1 will represent myTwoDimentionalArray[0][0], and E2 - myTwoDimentionalArray[4][1]. Where there are two, there are three. In Java, you can define 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 and means “arrays”). In general, the following operations are most often performed with arrays: filling with elements (initialization), extracting an element (by number), sorting, and searching. Finding and sorting arrays is a separate topic. On the one hand, it is very useful to practice and write several search and sorting algorithms on your own. On the other hand, all the best ways are already written and included in the Java libraries, and they are legal to use. Here are three useful methods of this class

Array sort

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

Search in the array for the desired element

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

Array to string conversion

The method String toString(int[] myArray)converts an array to a string. The thing is, in Java, arrays don't override toString() . This means that if you try to print an entire array (rather than element by element, as in “Displaying an Array ”) 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 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 print an array to the screen 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 an array output using toString , the third is a sorted array, the fourth is the index of the desired number 5 in the sorted array (remember that we count from zero, so the fourth element of the array has an index 3). In the fifth line we see the value -1 . There is no such index in an array. 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 are the type of data placed in it, the name and length.
    The latter is decided during initialization (memory allocation for the array), the first two parameters are determined when the array is declared.

  • The size of the array (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 from zero.

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

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

Arrays in Java - 5

Useful materials about arrays

Want to know more about arrays? Check out the articles below. There is a lot of interesting and useful information on this topic.
  1. Something about arrays - a good detailed article about 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 - Efficient Programming author Joshua Bloch talks about the best way to return empty arrays