Hello! Previously, during training, we worked with single objects (or primitive types). But what if we need to work not with one object, but with a whole group? For example, we want to create a list of birthdays of all employees in our company. It should contain, say, 30 lines in the format: “Andrey Petrov, January 25.” A special data structure, an array, will help us here. If you compare the array with objects from real life, its structure is very similar to a bank vault with cells: Something about arrays in Java - 1The array also consists of cells. You can put something in each cell. In this case, to access the content you need to know the cell number. The array is created like this:

public class Main {

   public static void main(String[] args) {

       String [] birthdays = new String[10]; // array of Java strings
      
   }
}
Here we have created an array of 10 cells. You can immediately pay attention to some features of the array:
  1. It stores data of a strictly defined type. If we initially created a string array String, we won't be able to store anything else in it. The data type is specified when creating the array. This is what distinguishes it from a safe deposit box, in which the client can store whatever he wants.
  2. An array can store data of primitive types (for example, int), strings ( String), or objects of the same class. More precisely, not even the objects themselves, but links to these objects.
  3. The size of the array must be specified during creation. You won't be able to specify it later or resize it after creation.
Java indicates that an array is being created by using square brackets []on both sides of the expression. They can be specified before the name of the reference variable or after - it will work either way:

//Java arrays of strings, two syntaxes
String [] birthdays = new String[10];
String birthdays [] = new String[10];
If you want to write something to an array, you need to specify the number of the cell in which the value will be written. Array cell numbers start at 0. Starting from zero is a common practice in programming. The faster you get used to it, the better :) Something about arrays in Java - 2That is, if you want to put some value in the first cell of the array , it is done like this:

public class Main {

   public static void main(String[] args) {

       String birthdays [] = new String[10];
       birthdays[0] = "Lena Eliseeva, March 12";
   }
}
Now the first cell of our array, which contains the birthdays of colleagues, contains a string with Lena’s birthday. By analogy, you can add other values:

public class Main {

   public static void main(String[] args) {

       String birthdays [] = new String[10];
       birthdays[0] = "Lena Eliseeva, March 12";
       birthdays[1] = "Kolya Romanov, May 18";
       birthdays[7] = "Olesya Ostapenko, January 3";
   }
}
Please note: we added Olesya’s birthday to the eighth cell (have you forgotten why cell No. 7 is the eighth?). Although all other cells are not filled in. It is not necessary to write the values ​​into the array in order - there is no such restriction. On the other hand, if you write in order, it will be much easier to keep track of the number of free and occupied cells, and there will be no “holes” left in the array. If you want to get the contents of an array cell, as in the case of a bank cell, you need to know its number. This is done like this:

public class Main {

   public static void main(String[] args) {

       String birthdays [] = new String[10];
       birthdays[0] = "Lena Eliseeva, March 12";
       birthdays[1] = "Kolya Romanov, May 18";
       birthdays[7] = "Olesya Ostapenko, January 3";

       String olesyaBirthday = birthdays[7];
       System.out.println(olesyaBirthday);
   }
}
Console output:

Олеся Остапенко, 3 января
We created a variable Stringand told the compiler: “Find the cell with index 7 in the array birthdaysand assign the value stored there to the variable String olesyaBirthday.” That's exactly what he did.

Java array length

When working with an array, you can easily find out its length using a special property - length.

public class Main {

   public static void main(String[] args) {

       String birthdays [] = new String[10];
       birthdays[0] = "Lena Eliseeva, March 12";
       birthdays[1] = "Kolya Romanov, May 18";
       birthdays[7] = "Olesya Ostapenko, January 3";

       int birthdaysLength = birthdays.length;
       System.out.println(birthdaysLength);
   }
}
Console output:

10
Note:The property lengthstores the size of the array, not the number of filled cells. Our array only stores 3 values, but when we created it, we specified size = 10 for it. This is the value that the field returns length. Why might this be useful? Well, for example, if you want to print a list of all birthdays to the console (to check that no one has been forgotten), you can do this in one simple loop:

public class Main {

   public static void main(String[] args) {

       String birthdays [] = new String[10];
       birthdays[0] = "Lena Eliseeva, March 12";
       birthdays[1] = "Kolya Romanov, May 18";
       birthdays[2] = "Vika Ignatova, July 12";
       birthdays[3] = "Denis Kozlov, September 7";
       birthdays[4] = "Maxim Maslennikov, November 9";
       birthdays[5] = "Roman Baranov, August 14";
       birthdays[6] = "Valery Pyatkina, April 1";
       birthdays[7] = "Olesya Ostapenko, January 3";
       birthdays[8] = "Kostya Gurko, October 19";
       birthdays[9] = "Seryozha Naumov, May 3";

       for (int i = 0; i < birthdays.length; i++) {
           System.out.println(birthdays[i]);
       }
   }
}
In the loop we create a variable ithat is initially equal to zero. On each pass, we take the cell with index i from our array and print its value to the console. The loop will make 10 iterations, and the values ​​of i will increase from 0 to 9 - just according to the indices of the cells of our array! This way we will print all the values ​​from birthdays[0]to to the console birthdays[9] . In fact, there are ways to create an array differently. For example, an array of numbers intcan be created like this:

public class Main {

   public static void main(String[] args) {
       int numbers [] = {7, 12, 8, 4, 33, 79, 1, 16, 2};
   }
}
This method is called “fast initialization”. It is quite convenient in that we immediately create an array and fill it with values. There is no need to explicitly specify the size of the array - the field lengthwill be filled in automatically during quick initialization.

public class Main {

   public static void main(String[] args) {
       int numbers [] = {7, 12, 8, 4, 33, 79, 1, 16, 2};
       System.out.println(numbers.length);
   }
}
Console output:

9

Java Object Array

You've already heard that arrays of objects and arrays of primitives are stored in memory differently. Let's take, for example, an array of three objects Cat:

public class Cat {

   private String name;

   public Cat(String name) {
       this.name = name;
   }

   public static void main(String[] args) {

       Cat[] cats = new Cat[3];
       cats[0] = new Cat("Thomas");
       cats[1] = new Cat("Hippopotamus");
       cats[2] = new Cat("Philip Markovich");
   }
}
There are a few things to understand here:
  1. In the case of primitives, Java arrays store many specific values ​​(such as numbers int). In the case of objects, an array stores many references. The array catsconsists of three cells, each of which contains a reference to an object Cat. Each of the links points to an address in memory where that object is stored.
  2. Array elements are stored in memory in a single block. This is done for more efficient and quick access to them. Thus, the link catspoints to a block in memory where all objects - the elements of the array - are stored. A cats[0]- to a specific address within this block.
Something about arrays in Java - 3It is important to understand that an array can not only store objects, it is itself an object.

Array of arrays or two-dimensional array

Based on this, we are faced with the question - can we create, for example, not an array of strings or numbers, but an array of arrays? And the answer will be - yes, we can! An array can store any objects within it, including other arrays. Such an array will be called two-dimensional. If you depict it in a picture, it will look very similar to a regular table. For example, we want to create an array that will store 3 arrays of numbers intwith 10 cells each. It will look like this: Something about arrays in Java - 4Each line represents an array of numbers int. The first array contains numbers from 1 to 10, the second - from -1 to -10, the third - a set of random numbers. Each of these arrays is stored in a cell of our two-dimensional array. Initializing a two-dimensional array in code looks like this:

public static void main(String[] args) {
   Cat[][] cats = new Cat[3][5];
}
Our two-dimensional cats array stores 3 arrays of 5 cells each. If we want to put our object in the third cell of the second array, we do it like this:

public static void main(String[] args) {
   Cat[][] cats = new Cat[3][5];
   cats[1][2] = new Cat("Fluff");
}
[1]points to the second array, and [2]points to the third cell of this array. Since a two-dimensional array consists of several arrays, in order to traverse it and print all the values ​​to the console (or fill all the cells), we need a double, nested loop:

for (int i = 0; i < cats.length; i++) {
   for (int j = 0; j < cats[i].length; j++) {
       System.out.println(cats[i][j]);
   }
}
In the outer loop (variable i), we take turns traversing all the arrays that make up our two-dimensional array. In the inner loop (variable j) we iterate through all the cells of each array. As a result, the object cats[0][0](first array, first cell) will be displayed first on the console, and the second object will be cats[0][1](first array, second cell). When the first array is exhausted, , cats[1][0], cats[1][1]and cats[1][2]so on will be output. By the way, fast initialization is also available for two-dimensional arrays:

int[][] numbers = {{1,2,3}, {4,5,6}, {7,8,9}};
Normally, we would write a two-dimensional array numbersas int[3][3], but this method allows us to immediately specify the values. Why might a two-dimensional array be needed? Well, for example, with its help you can easily recreate the famous game “Battleship”: Something about arrays in Java - 5The structure of the playing field in “Battleship” is such that it can be easily described: a two-dimensional array of 10 arrays, 10 cells each. You create two such arrays - for yourself and your opponent:

int [][] seaBattle = new int[10][10];
int [][] seaBattle2 = new int[10][10];
You fill in with some values ​​(for example, numbers or signs *) the cells in which your ships are located, and then you and your opponent take turns calling the cell numbers:
  • seaBattle[6][5]!
  • Past! seaBattle2[6][6]!
  • Injured!
  • seaBattle2[6][7]!
  • Injured!
  • seaBattle2[6][8]!,
  • Killed!

Additional resources 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. Arrays in Java - a detailed article about arrays, their creation, initialization and use. With examples.
  2. The Arrays class and its use - the article describes some methods of the classArray
  3. Arrays is the first JavaRush lecture dedicated to arrays.
  4. Multidimensional arrays - a detailed article about multidimensional arrays with examples.
  5. Return a zero-length array, not null - Effective Programming author Joshua Bloch talks about how to better return empty arrays.
This concludes our first acquaintance with arrays, but this is only the beginning of interaction with them. In the following lectures we will see interesting ways to use them, and also find out what built-in functions Java has for more convenient working with this data structure :)