Arrays. Java Array

An array is a collection of variables of the same type that are referred to by a common name. Arrays can be created from elements of any type, and they can have one or more dimensions. TO specific element in an array they are accessed by its index (number). In this note we will look at processing one-dimensional and two-dimensional arrays.

One-dimensional arrays in Java

A one-dimensional array is essentially a list of variables of the same type. To create an array, you must first create an array variable of the desired type. The general format for declaring a one-dimensional array is:
type var-name ;
Here type declares the underlying type of the array; var-name is the name of the array variable. The base type determines the data type of each array element. For example, a declaration of a one-dimensional array of int components named month_days looks like:
int month_days ;
Although this declaration establishes the fact that month_days is an array variable, no array actually exists. In fact, month_days is set to null (null pointer), which represents an array with no value. To associate month_days with an actual, physical array of integers, you need to allocate memory for it using the new operation and assign it to the month_days array; new is a special operation that allocates memory.

The general format of new as applied to one-dimensional arrays is:
array-var = new type ;
where type is the type of data being distributed, size is the number of elements in the array, array-var is a variable that is associated with the array. To use new to allocate memory for an array, you need to specify the type and number of array elements. Elements in the array allocated with the new operation will be automatically initialized to zero. The following example allocates memory for a 12-element array of integers and associates it with the month_days variable.
month_days = new int;
After this statement executes, month_days will refer to an array of twelve integers. Then all elements in the array will be initialized to zero.
The process of obtaining an array involves two steps. First, you must declare an array variable of the desired type. Second, you need to allocate the memory that will contain the array using the new operation and assign it to an array variable. Thus, in Java all arrays are dynamically allocated.

Once you have allocated memory for an array, you can access a specific element in it by pointing to square brackets index. The numbering of array elements starts from zero. Array names are references.

Possible ad combination variable type an array with allocation of memory to the array directly in the declaration:
int month_days = new int;

Consider the code of a program that replaces negative elements of an array with the maximum element:

Public class FindReplace ( public static void main(String args) ( int myArray; // declaration without initialization int mySecond = new int; /* memory allocation with initialization to default values ​​*/ int a = (5, 10, 0, -5 , 16, -2); // declaration with initialization int max = a; for (int i = 0; i< a.length; i++) { if (a[i]<0) a[i] = max; mySecond[i] = a[i]; System.out.println("a[" + i + "]=" + a[i]); } myArray = a; // установка ссылки на массив a } }

The result of execution will be:

>java FindReplace a=5 a=10 a=0 a=5 a=16 a=5

Assigning mySecond[i] = a[i] will cause part of the elements of the array mySecond , namely six, to be assigned the values ​​of the elements of the array a . The remaining elements of mySecond will retain the values ​​obtained during initialization, that is, zeros. If the assignment is organized in the form mySecond = a or myArray = a, then both arrays participating in the assignment will receive a reference to the array a, that is, both will contain six elements and refer to the same memory location.
Arrays can be initialized at the time they are declared. The process is much the same as that used to initialize simple types. An array initializer is a comma-separated list of expressions surrounded by curly braces. The array will automatically be created large enough to contain as many elements as you specify in the array initializer. There is no need to use the new operation. For example, to store the number of days in each month, the following code creates an initialized array of integers:

Public class MonthDays ( public static void main(String args) ( int month_days = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); System.out.println("April contains " + month_days + " days."); ) )

As a result of executing the program, the following will be displayed on the screen:

April contains 30 days.

Comment: Java makes strict checks to make sure you don't accidentally try to store or read values ​​outside of the array's storage area. Executive system Java also makes careful checks to ensure that all array indices are in the correct range. (In this regard Java differs significantly from languages C/C++, which do not provide run-time bounds checking).

Multidimensional Arrays in Java

IN Java multidimensional arrays are, in fact, arrays of arrays. They look and act like regular multidimensional arrays. However, there are a couple of subtle differences. To declare a multidimensional array variable, define each additional index using a different set of square brackets. For example, the following statement declares a two-dimensional array variable named twoD:
int twoD = new int;
It allocates memory for a 4x5 array and assigns it to the twoD variable. Internally, this matrix is ​​implemented as an array of arrays of integers of type int .
Multidimensional arrays can be initialized. To do this, simply include the initializer of each dimension in its own set curly braces.
IN next program Arrays of arrays of equal length (matrices) are created and initialized, and the product of one matrix by another is performed:

Public class Matrix ( private int a; Matrix(int ​​n, int m) ( // creation and filling with random a = new int[n][m]; for (int i = 0; i< n; ++i) for (int j = 0; j < m; ++j) a[i][j] = (int) (Math.random()*5); show(); } public Matrix(int n, int m, int k) { // создание и заполнение с random a = new int[n][m]; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) a[i][j] = k; if (k != 0) show(); } public void show() { System.out.println("Матрица:" + a.length + " на " + a.length); for (int i = 0; i < a.length; ++i) { for (int j = 0; j < a.length; ++j) System.out.print(a[i][j] + " "); System.out.println(); } } public static void main(String args) { int n = 2, m = 3, z = 4; Matrix p = new Matrix(n, m); Matrix q = new Matrix(m, z); Matrix r = new Matrix(n, z, 0); for (int i = 0; i < p.a.length; ++i) for (int j = 0; j < q.a.length; ++j) for (int k = 0; k < p.a[i].length; ++k) r.a[i][j] += p.a[i][k]*q.a[k][j]; System.out.println("Произведение матриц: "); r.show(); } }

Since values ​​are assigned to array elements using the random() method, one of the options for executing the code could be the following:

> javac Matrix.java > java Matrix Matrix:2 by 3 3 2 0 3 3 1 Matrix:3 by 4 1 2 2 3 3 2 3 2 1 2 3 2 Product of matrices: Matrix:2 by 4 9 10 12 13 13 14 18 17

The following example demonstrates copying an array:

Public class ArrayCopyDemo ( public static void main(String args) ( int mas1 = (1,2,3), mas2 = (4,5,6,7,8,9); System.out.print("mas1: " ); show(mas1); System.out.print("mas2: "); // copying the mas1 array to mas2 System.arraycopy(mas1, 0, mas2, 2, 3); mas1 is copied starting from the zero element * 2 - the element from which the replacement begins * 3 - the number of elements to be copied */ System.out.println("\n after arraycopy(): "); System.out.print("mas1: " ); show(mas1); System.out.print("\nmas2: "); private static void show(int mas) ( for (int i = 0; i< mas.length; ++i) System.out.print(" " + mas[i]); } }

Result of program execution:

> javac ArrayCopyDemo.java > java ArrayCopyDemo mas1: 1 2 3mas2: 4 5 6 7 8 9 after arraycopy(): mas1: 1 2 3 mas2: 4 5 1 2 3 9

Alternative Array Declaration Syntax

There is another form that can be used to declare an array:
type var-name;
Here the square brackets follow the type specifier rather than the array variable name. For example, the following two declarations are equivalent:

Int al = new int; int a2 = new int;
The declarations presented here are also equivalent:
char twodi = new char; char twod2 = new char;
This alternative form of announcement is included primarily for convenience.

An array is a set of objects of the same type that have a common name. Each array element can be accessed by its index. Let's consider real example. Let us have a certain warehouse called a and let it have a certain number of boxes, each of which is numbered sequentially. Each box contains an object that is the same type as the objects in other boxes. An example of this warehouse is a classic array, where the name of the warehouse is the name of the array, the boxes are the elements of the array, the box numbers are the indices of the elements, and the contents of the boxes are the values ​​of our variables. Let's imagine that there are lemons inside the boxes, and in each box there is a certain amount lemons. Then, the values ​​of our variables will show the number of lemons. Consider a warehouse consisting of three boxes, let the first box contain 3, the second 7, and the third 273. Then, the array describing this warehouse can be depicted as follows:

Index 0 1 2
Meaning 3 7 273

Indexing in an array always starts at 0. Let's look at some operations that can be performed with an array:

Creating an Array

TypeVariableName;
int a;//integer array
char b;//character array
String c;

Memory allocation:

A = new int;//allocate memory for 10 elements
b = new char;//allocate memory for 20 elements
c = new String;//allocate memory for 30 elements

Thus, array initialization looks like this:

Int a = new int;//initializing an array of integers with 10 elements
char b = new char;//initializing a 20-element character array
String c = new String;//initializing a string array of 30 elements

All elements of the array after such initialization are assigned a default value.
It is possible to immediately set the values ​​of the array elements; let’s create an array that will show the number of lemons in the box, as in the example above:

Int a = new int( 3, 7, 273 );

Working with an array

Reading an array:

Import java.util.Scanner;
public class test (
public static void main(String args) (
int a;//array of integers
int n;//number of elements in the array
Scanner in = new Scanner(System.in);
n = in.nextInt();
a = new int[n];
for(int i = 0; i Changing array values:


for(int i = 0; i Array output:

Int a;//an array of integers that has been processed somehow
for(int i = 0; i Random access to an array element by index:

System.out.println(a);//Print the first element of the array
a = 1;//Assign 1 to the second element of the array
int temp = a;//Save the value of the third element of the array into the temp variable

This is what basic operations with arrays look like. Very often in various computer science lessons they are asked to separate these stages of working with an array into separate functions, but we will talk about this later. Thus, by reading an array, we can enter some values ​​from the console, by changing values, we can, for example, increase all values ​​by one or multiply by two, and by using output, we can display the current values ​​of the array. If we only need to work with specific elements array, then we can use random access by index, where index is any positive integer that less length array. The current length of the array can be obtained using length properties, it was already used when outputting the array.
Here I will omit the dialogue about the fact that arrays are references and working with them differs from working with ordinary base types.

Two-dimensional arrays

It is not always convenient to number boxes in a warehouse from 0 to a certain number; sometimes you want to bring the warehouse into a more orderly form, for example, introduce rows. Now each box has its own row number and its own serial number in this row. Let there be nine boxes in our warehouse that contain 1, 2, and so on 9 oranges. The boxes in the warehouse are arranged in three rows of three boxes, then the situation in the warehouse can be imagined as follows.

1. What are arrays?

This is a special structure that exists in almost every programming language, allowing you to describe a group of objects of the same type using a common name.

Let's imagine that you have a homeless animal shelter with five cats. You don’t remember everyone’s name, but everyone has a tag with a number that allows you to identify each animal. We can say that this is an array of cats of size five. Please note that indexing starts from zero - this is customary in Java. If it were not possible to create arrays, you would have to declare five variables and come up with names for them, which is not very convenient.

In Java, you can create arrays of any size - one-dimensional, two-dimensional, three-dimensional, etc. Let's start with the simplest option - one-dimensional arrays.

2. One-dimensional arrays

One-dimensional arrays are a list of variables of the same type. To create an array, you must first declare an array variable of the required type. General form The declaration of a one-dimensional array looks like this:

TypeVariableName;

where is the parameter type denotes the type of an array element, also called the base type.

Example 1. Example of declaring arrays

Square brackets can be placed before or after a variable. But a more correct option is to indicate parentheses before the variable - this way the type and the parentheses are in the same place, which allows you to understand at first glance that this is an array of this type.

Int monthDays; double monthSalaries;

2.1. Initializing an array using a keyword new

When an array is declared, memory has not yet been allocated for it. To allocate memory for an array, use the keyword new, after which the array type is again indicated and the size in square brackets:

VariableName = new type[size];

An array can be declared and initialized in one line:

Int values ​​= new int;

Example 2. Example of an array declaration

Let's look at an example of declaring an array of type int size 12 by in this example. After executing the line int monthDays = new int an array of 12 elements has been created. Each element is assigned a default value for given type. For type int it's zero. To contact individual element of the array after the array name in square brackets we set the index of the element. This way we can access an array element to change or get its value.

Public class Array1 ( public static void main(String args) ( int monthDays = new int; monthDays = 31; monthDays = 28; monthDays = 31; monthDays = 30; monthDays = 31; monthDays = 30; monthDays = 31; monthDays = 31 ; monthDays = 30; monthDays = 30; monthDays = 31; System.out.println("In April " + monthDays + " days.");

2.2. Initializing an Array Using an Initialization Block

Example 3. Example of initializing a one-dimensional array

If you know the values ​​for each element of the array in advance, you can use a block to initialize the array. Instead of new int, V curly braces The values ​​of the array elements are separated by commas. The size of the array is inferred by the compiler from the number of specified elements.

Public class Array2 ( public static void main(String args) ( int monthDays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); System.out.println("B April " + monthDays + " days."); ) )

2.3. Unnamed array

There is also a third form of declaring an array - an unnamed array. It can be used in two cases. First - you declared and initialized the array testScores size four , but then for some reason it has to be changed - it has to contain three elements. You cannot reuse the form to initialize an array - there will be a compilation error:

Int testScores = (1, 2, 3, 4); ... testScores = (4, 7, 2); //compilation error

But you can use an unnamed array, which will create a new array in memory. The form of writing an unnamed array is a mix of the first two:

TestScores = new int(4, 7, 2);

The second use case for an unnamed array is when passing the array to a method. In the following example, the method print takes as input an array of type int. When calling a method, you can pass an unnamed array as an argument.

Example 4. An example of an unnamed array

public class Array3 ( public static void main(String args) ( int testScores = (1, 2, 3, 4); for (int element: testScores) ( System.out.print(element + " "); ) System.out .println(); testScores = new int(4, 7, 2); for (int element: testScores) ( System.out.print(element + " "); ) System.out.println(); (4, 6, 2, 3)); public static void print(int array) ( for (int element: array) ( System.out.print(element + " "); ) ) )

3. Multidimensional arrays

Multidimensional arrays are arrays of arrays.

When declaring a multidimensional array variable, a separate row of square brackets is used to indicate each additional index. For example:

Int twoD = new int;

The following figure shows how you can visually represent a two-dimensional 4 by 5 array. The left index defines the row, and the right column.

Example 5: Two-dimensional array example

The following example demonstrates how you can set values ​​in a 4x5 two-dimensional array. An outer loop is used to iterate through strings for, for iterating over columns - internal. Each next element is assigned a value one greater than the previous one.

Public class TwoDArray1 ( public static void main(String args) ( int twoD = new int; int i, j, k = 0; for (i = 0; i< 4; i++) { for (j = 0; j < 5; j++) { twoD[i][j] = k++; System.out.print(twoD[i][j] + " "); } System.out.println(); } } }

3.2. Representation of a multidimensional array in memory

Let us now consider how the array is represented int twoD = new int; in memory. Variable twoD does not point to a matrix, but to a row (red) consisting of three elements. The value of each element is a reference to a string of four elements (colored purple).

The following picture shows how a three-dimensional array is stored int threeD = new int in memory:

An array of any size can be stored in memory in this way.

In the two-dimensional arrays we've looked at so far, the number of elements in each row is the same - most often this is the case. But this is not necessary; each line can contain a different number of elements. For example:

Example 6. Example of a two-dimensional array with different dimensions

Let's look at the code that implements such an array. When declaring an array, you must specify the number of elements only for the first dimension - int array = new int. Thus, we indicate the number of lines in the array, but we do not allocate memory for each line. Next, we allocate separate memory for each row of the array. For example, a row with index zero will be of size 1 - array = new int.

Public class TwoDArray2 ( public static void main(String args) ( int array = new int; array = new int; array = new int; array = new int; array = new int; int i, j, k = 0; for ( i = 0;< 4; i++) { for (j = 0; j < i + 1; j++) { array[i][j] = k++; System.out.print(array[i][j] + " "); } System.out.println(); } } }

3.4. Block for initializing a multidimensional array

Example 7: Initializing a two-dimensional array

For multidimensional arrays, you can also use a block for initialization if the values ​​of all elements are known in advance. Each individual line is enclosed in curly braces:

Public class TwoDArray3 ( public static void main(String args) ( double arrayTwoD = ( (0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15) ); for (double arrayOneD: arrayTwoD) ( for (double element: arrayOneD) ( System.out.print(element + " "); ) System.out.println(); ) ) )

3.4. Array length

Example 8: Getting the length of an array

The following example demonstrates how to get the length of an array. For this purpose the variable is used length. With a one-dimensional array, everything is clear - its length is the number of its elements. The length of a multidimensional array is the number of elements of its first dimension. For example, array length array2 is 2. You can also get the length of each row of the array. For example, array2.length- will return the number of elements in the row with index zero.

Public class ArraySize ( public static void main(String args) ( int array1 = (1, 2, 3, 4); int array2 = ((1, 1, 1), (2, 2, 2)); System.out .println("Size of array1 = " + array1.length); System.out.println("Size of array2 = " + array2.length); System.out.println("Size of 1-row array array2 = " + array2 .length);

Execution result:

Array size array1 = 4 Array size array2 = 2 Array 1-row size array2 = 3

4. Useful techniques when working with arrays

There are a number of methods that are useful when working with arrays. Let's look at them:

4.1. Method Arrays.toString()

The method returns a string representation of a one-dimensional array, separated by commas. Instead of looping through arrays for, as we did in example 4, you can use this method to output elements to the console:

Example 9. Application of the method Arrays.toString()

import java.util.Arrays; public class ArraysToStringDemo ( public static void main(String args) ( int array = (1, 4, 6, 3, 8); System.out.println(Arrays.toString(array)); ) )

4.2. Method Arrays.deepToString()

The method returns a string representation of a multidimensional array, highlighting the lines with square brackets:

Example 10. Application of the method Arrays.deepToString()

import java.util.Arrays; public class ArraysDeepToStringDemo ( public static void main(String args) ( String array = (("one-one", "one-two", "one-three"), ("two-one", "two-two", "two-three")); System.out.println(Arrays.deepToString(array) ) )

4.3. Method Arrays.sort()

Method Arrays.sort() sorts the elements of a numeric array in ascending order:

Example 11. Sort an array

import java.util.Arrays; public class ArraysSort1 ( public static void main(String args) ( int array = new int(3, 1, 5, 6, 8); Arrays.sort(array); System.out.println(Arrays.toString(array)) ; ) )

4.4. Method Arrays.binarySearch()

Method Arrays.binarySearch() searches an array for a given value and returns the element number. If the searched element is not found, it returns -(position + 1), Where position- the position of the element where it COULD BE. The array must be sorted, otherwise the result of the method call will be undefined:

Example 12: Finding an Array Element

import java.util.Arrays; public class BinarySearch1 ( public static void main(String args) ( int array1 = (10, 20, 30, 40); int pos1 = Arrays.binarySearch(array1, 20); int pos2 = Arrays.binarySearch(array1, 25); System.out.println(pos1); System.out.println(pos2) )

Execution result:

4.5. Method System.arraycopy()

Method System.arraycopy() allows you to copy part of an array to another array.

Example 13: Copying an array

Let's look at an example that copies elements 2,3,4 from an array arraySource to array arrayDestination:

Import java.util.Arrays; public class ArrayCopy1 ( public static void main(String args) ( int arraySource = (1, 2, 3, 4, 5, 6); int arrayDestination = (0, 0, 0, 0, 0, 0, 0, 0) ; System.out.println("arraySource: " + Arrays.toString(arraySource)); System.out.println("arrayDestination: " + Arrays.toString(arrayDestination)); , 3); System.out.println("arrayDestination after arrayCopy: " + Arrays.toString(arrayDestination) )

Execution result:

ArraySource: arrayDestination: arrayDestination after arrayCopy:

Example 14. Copying an array from itself to itself

You can copy to the same array with overlapping areas:

Import java.util.Arrays; public class ArrayCopy2 ( public static void main(String args) ( int array = (1, 2, 3, 4, 5, 6, 7, 8); System.out.println(Arrays.toString(array)); System. arraycopy(array, 1, array, 3, 3); System.out.println(Arrays.toString(array) )

Execution result:

Let's start with perhaps the last not very pleasant and interesting, but very important and useful topic in the theory of the Java language - arrays. Next there will be more interesting and exciting material that can be used for more practical tasks. But in order to start the interesting part of Java, you need to learn the uninteresting part)) which is the basis of the language and without which it is impossible to further learn programming.

All the previous topics we covered: are the basics of programming. By studying them you will begin any other programming language. Arrays also relate to this topic. Whatever you decide to start programming with, you are unlikely to be able to do without arrays. Therefore, I advise you to master this and past material very well if you want to succeed in programming.

Now let's move on to arrays.

Array is a data structure that is designed to store data of the same type.

Let's say you need to create 5 integer variables and set them to some value. How will you do this? Without knowing arrays, you will most likely start writing like this: int a = 2, b = 3, c = 5, d = 21, e = 2;

Having such a data type as arrays in your arsenal, you can write like this: int a = (2, 3, 5, 21, 2);

This is very convenient when processing this data takes place. For example, now you need to add 3 to each variable. If you used the first method of declaration, then such an operation would take you quite a lot of time. Whereas, having arrays and in our arsenal, we can process huge amount data without resorting to monotonous code.

Before using the array you need:

  1. announce;
  2. Create;
  3. Initialize.

Remember this procedure and never break it.
Declaring arrays:
char s;
String p;
or
char s;
String p;
Creating arrays:
s = new char;
p = new String;

The number of array elements is indicated in square brackets. This quantity it is forbidden will change later.
Initializing arrays:
after creation - element by element: int a = (1,2,3,4,5);
when declaring/creating – the entire array: int b = new int (2, 4,6);.

If the array is not explicitly initialized, then after its creation everything
elements are equal:
0 – in numeric arrays
false – in boolean arrays
null – in arrays of objects

Array boundaries:
All arrays have a length field - the length of the array (in elements)
The first element always has index 0 (not to be confused with the value).
The last element always has index length-1.

After so much theory, I think a little practice is needed:

    public class ArraysInJava(

    int Array; //array declaration

    intArray = new int [ 10 ] ; //array initialization

    intArray[ 0] = 1 ; //give the first element of the array the value 1

    intArray[ 1] = 2 ; //second value 2

    intArray[ 6] = 7 ; //the remaining values ​​of the array that we use

    //no values ​​specified will be 0 by default

    //corresponds to the value in square brackets during initialization.

    for (int i = 0 ; i< intArray.length ; i++ ) {

    for (int i = 0 ; i< intArray.length ; i++ ) {

    intArray[ i] = 45 ; //each element of the array can be changed

Result of executing the code:

We have reviewed one-dimensional arrays in Java. Now it's the turn of the two-dimensional ones.

As you might have guessed, a two-dimensional array is an array of arrays. No need to be scared. Everything is much simpler than it seems.

int twoDim = new int - this is how you can declare a two-dimensional array with a dimension of 4 by 4. There will be 4 elements vertically and 4 horizontally. Setting a value for such an array is as simple as for a one-dimensional one: twoDim = 3. This entry will mean that we have assigned our array element, which is located in the second row (index starts at 0) and 3rd column. In the picture it will look like this:

By the way, here is a code example:

Multidimensional arrays can have any number of dimensions. Declaring, initializing and working with them is identical to one-dimensional arrays. If you learn to work with one-dimensional and two-dimensional arrays, then there will be no problems with three-dimensional and higher ones.

Another example. More precisely, a task. I want you to think and write an application that prints numbers in this order:

Hint: System.out.println(); - prints on a new line, whereas: System.out.print() - prints on the same line.

Before looking at the solution, try writing it yourself. This really reinforces the material covered.

For those who haven’t mastered it, I offer a solution. Don't be upset. Programming takes time and patience.

    public class FormatMatrixPrint (

    int size = 5 ;

Imagine cells in a storage room. Each of them has its own number, and each of them stores 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 specific number. In Java, to work with similar structures, that is, a lot of homogeneous data, arrays 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 index. In the case of Java, an array homogeneous, that is, all its cells will store elements of the same type. Thus, an integer array contains only integers (for example, type int), an array of strings - 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.

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 it was left alternative way). The table shows both ways of declaring an array 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 declaring an array, it has a name and type (type 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 ints. 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 declaration using this shorthand syntax: int myArray = new int [ 10 ] ; // declaration and memory allocation “in one package” Please note: After creating the array with using new, its cells contain 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.

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. Please note: in Java elements arrays are numbered 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. 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) ; // display the length of the array in the console, 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 contains a null value (since string is a reference type) */ seasons[ 0 ] = "Winter" ; /* to the first cell, that is, to the cell with zero number we wrote down the line Winter. Here we access 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 from 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 for loop. Another, shorter way to display an array on the screen will be discussed in paragraph “. 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 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 taught the beginnings of linear algebra, on a matrix. Why 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, myTwoDimentionalArray, myTwoDimentionalArray, myTwoDimentionalArray and so on up to myTwoDimentionalArray. So if we use it to represent a chessboard, then cell A1 will be represented by myTwoDimentionalArray , and cell E2 will be represented by myTwoDimentionalArray . 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.

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, everything best ways have already been written and included in Java libraries and can be legally used.

Articles to search and sort:

Sorting and searching in the CS50 course:

Here are three useful methods of this class

Sort an array

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

Searching an array for the desired element

int binarySearch(int myArray, int fromIndex, int toIndex, int key) . This method looks for the key element in already sorted array myArray or subarray, starting from fromIndex and ending with toIndex . If the element is not found, returns the element number or fromIndex-1 .

Converting an Array to a String

The String toString(int myArray) method converts an array to a string. The thing is that in Java arrays do not override toString() . This means that if you try to withdraw whole array(not element by element as in “ ”) to the screen directly (System.out.println(myArray)), you will get the class name and the hex hash code of the array (this is defined by Object.toString()). If you are a beginner, you may be confused about the explanation of the toString method. 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. This is discussed in the example below.

Example on sort, binarySearch and toString

Let's create an array of integers, print it to the screen using toString , sort it using sort method and 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); //trying to display our array on the screen without the toString method - we get a hexadecimal number//print the array "correctly" Arrays. sort(array, 0, 4); //sort the entire array from zero to fourth member System. out. println(Arrays. toString(array)); //display the sorted array on the screen int key = Arrays. binarySearch(array, 5); // looking for key - the number 5 in the sorted array. //the binarySearch method will return the index of the element of the sorted array in which the searched number is “hidden” System. out. println(key); //print the index of the required number System. out. println(Arrays. binarySearch(array, 0)); //now let's try to find a number that is not in the array, // and immediately display the result on the screen } } Program output: 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 the 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 -1. An array does not have such an index. The output signals that the searched element (in in this case, 0) is not in the array.

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.

    Array in Java language differs significantly from an array in C++. However, it is practically the same as a pointer to a dynamic array.

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.

    Something about arrays - good detailed article about arrays

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

    Arrays is the first JavaRush lecture dedicated to arrays.

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