Two-dimensional arrays in java. Arrays in Java. One-dimensional and multidimensional

  • Tutorial

I think that few of those preparing for their first interview, when applying for their first job as a (pre)junior programmer, will answer this question in the negative. Or at least doubt the positive answer. Of course, such a simple data structure with direct index access - no tricks! No, in some languages ​​like JavaScript or PHP, arrays are, of course, implemented in a very interesting way and are essentially much more than just an array. But this is not what we are talking about, but about the “traditional” implementation of arrays in the form of a “continuous piece of memory”. In this case, based on the indices and the size of one element, the address is simply calculated and the corresponding value is accessed. What's so difficult about it?
Let's figure it out. For example, in Java. Asking an unsuspecting applicant to create an array of integers n x n. The person confidently writes something like:
int g = new int[n][n];
Great. Now we ask you to initialize the array elements with something. At least in units, at least as a sum of indices. We get:
for(int i = 0; i< n; i++) { for(int j = 0; j < n; j++) { g[i][j] = i + j; } }
They even write more often
for(int i = 0; i< g.length; i++) { for(int j = 0; j < g[i].length; j++) { g[i][j] = i + j; } }
which is also a reason for conversation, but now we are talking about something else. We are trying to find out what a person knows and see how he thinks. Therefore, we draw his attention to the fact that the values ​​are located symmetrically and ask him to save on loop iterations. Of course, why go through all the index values ​​when you can only go through the bottom triangle? The subject usually easily agrees and wisely highlighting the main diagonal, carefully writes something like:
for(int i = 0; i< n; i++) { g[i][i] = 2* i; for(int j = 0; j < i; j++) { g[j][i] = g[i][j] = i + j; } }
Instead of g[i][i] = 2* i; often written g[i][i] = i + i; or g[i][i] = i<< 1; и это тоже повод поговорить. Но мы идем дальше и задаем ключевой вопрос: How much faster will the program run?. The usual reasoning is as follows: almost 2 times less index calculations; almost 2 times less calculations of values ​​(summing); the same number of assignments. This means 30 percent faster. If a person has a good mathematics background, then you can even see the exact number of saved operations and a more reasoned assessment of the effectiveness of optimization.
Now is the time for the main blow. We run both versions of the code on some sufficiently large value n(about several thousand), for example, like this.

Time controlled code

class A ( public static void main(String args) ( int n = 8000; int g = new int[n][n]; long st, en; // one st = System.nanoTime(); for(int i = 0;< n; i++) { for(int j = 0; j < n; j++) { g[i][j] = i + j; } } en = System.nanoTime(); System.out.println("\nOne time " + (en - st)/1000000.d + " msc"); // two st = System.nanoTime(); for(int i = 0; i < n; i++) { g[i][i] = i + i; for(int j = 0; j < i; j++) { g[j][i] = g[i][j] = i + j; } } en = System.nanoTime(); System.out.println("\nTwo time " + (en - st)/1000000.d + " msc"); } }


What do we see? The optimized version works 10-100 times slower! Now is the time to observe the candidate's reaction to the position. What will be the reaction to an unusual (more precisely, usual in the developer’s practice) stressful situation. If the defendant’s face shows excitement and he begins to press buttons, temporarily forgetting about your existence, then this is a good sign. To a certain extent. You don't want to hire a researcher who doesn't care about the outcome of the project, do you? Then don't ask him the question "Why?" Ask them to rework the second option so that it actually works faster than the first.
Now you can safely go about your business for a while. In half an hour you will have enough material to assess the basic personal and professional qualities of the applicant.
By the way, when I briefly described this problem on my work site, the most popular comment was “This is your Java curve.” I’m posting the code on Great and Free especially for them. And happy owners of Free Pascal for Windows can take a look

under the spoiler

program Time; usesWindows; var start, finish, res: int64; n, i, j: Integer; g: Array of Array of Integer; begin n:= 10000; SetLength(g, n, n); QueryPerformanceFrequency(res); QueryPerformanceCounter(start); for i:=1 to n-1 do for j:=1 to n-1 do g := i + j; QueryPerformanceCounter(finish); writeln("Time by rows:", (finish - start) / res, " sec"); QueryPerformanceCounter(start); for i:=1 to n-1 do for j:=1 to n-1 do g := i + j; QueryPerformanceCounter(finish); writeln("Time by cols:", (finish - start) / res, " sec"); end.


In the above code in Pascal, I removed the “confusing” aspects and left only the essence of the problem. If this can be called a problem.
What questions do we end up asking the defendant?
1. Why is it working slower? And in more detail...
2. How to make initialization faster?

If there is a need to dig deeper into the Java implementation, then we ask the applicant to observe the execution time for small values n. For example, on ideone.com for n=117, the “optimized” option is half as slow. But for the next value n=118 it turns out to be 100 (one hundred) times faster than the non-optimized one! Suggest experimenting on a local machine. Let him play with the settings.
By the way, does everyone understand what’s going on?

A few words of justification

I would like to say a few words to justify this method of hiring interviews. Yes, I do not test knowledge of language syntax and knowledge of data structures. Perhaps, in a civilized labor market, this all works. But in our conditions of a total shortage of qualified personnel, it is necessary to evaluate rather the long-term adequacy of the applicant for the work with which he will be faced. Those. the ability to learn, to break through, to understand, to do.
This is similar in spirit to the “interview” for recruiting legionnaires in ancient Rome. The future warrior was greatly frightened and watched to see if he blushed or turned pale. If he turns pale, then in a stressful situation the blood drains from the applicant’s head and he is prone to a passive reaction. For example, fainting. If the applicant blushed, then the blood rushed to his head. Those. he is prone to active actions and rushing into fights. This one was considered suitable.
Well, one last thing. Why did I tell everyone about this problem instead of continuing to use it in interviews? It’s just that potential applicants have already “learned” this task and have to use others.
Actually, I paid attention to this effect precisely in connection with the real task of image processing. The situation was somewhat confusing and I didn’t immediately understand why my fps dropped so much after the refactoring. In general, everyone probably has a lot of such wonderful moments.

So far the leading version is that the processor cache is to blame. Those. sequential access in the first option works within a hash, which is updated when moving beyond a certain boundary. When accessing by columns, the hash is forced to constantly update and this takes a lot of time. Let's check out this version in its purest form. Let's create an array and compare what is faster - to process all the elements in a row or to process the array elements with a random number the same number of times? This program is ideone.com/tMaR2S. For 100,000 array elements, random access is usually noticeably faster. What does this mean?
Here it was quite rightly pointed out to me (Big_Lebowski) that rearranging the loops changes the results in favor of the sequential option. For the purity of the experiment, I had to set up a warm-up cycle. At the same time, I did several repetitions to get the average operating time as Leventov advised. It turned out like this ideone.com/yN1H4g. Those. Random access to elements of a large array is ~10% slower than sequential access. Perhaps the cache may actually play some role. However, in the original situation, performance dropped significantly. So there is something else.

Gradually, the version about additional actions when moving from one row of an array to another is becoming the leader. And it is right. It remains to figure out what exactly is happening there.

Tags: Add tags

19 answers

You can use an array declaration or an array literal (but only when you immediately declare and affect a variable; array literals cannot be used to reassign an array).

For primitive types:

Int myIntArray = new int; int myIntArray = (1,2,3); int myIntArray = new int(1,2,3);

For classes like String it's the same:

String myStringArray = new String; String myStringArray = ("a","b","c"); String myStringArray = new String("a","b","c");

The third method of initialization is useful when you first declare an array and then initialize it. A cast is needed here.

String myStringArray; myStringArray = new String("a","b","c");

There are two types of array.

One dimensional array

Default value syntax:

Int num = new int;

Or (less preferred)

Int num = new int;

Syntax with specified values ​​(variable/field initialization):

Int num = (1,2,3,4,5);

Or (less preferred)

Int num = (1, 2, 3, 4, 5);

Note. For convenience, int num is preferred because it clearly states that you are talking about an array here. Otherwise there is no difference. Not at all.

Multidimensional array

Declaration

int num = new int;

Int num = new int;

Int num = new int;

Initialization

num=1; num=2; num=1; num=2; num=1; num=2; num=1; num=2; num=1; num=2;

Int num=( (1,2), (1,2), (1,2), (1,2), (1,2) );

Ragged Array (or non-rectangular array)

int num = new int; num = new int; num = new int; num = new int; num = new int;

So here we explicitly define the columns.
Another way:

Int num=( (1), (1,2), (1,2,3,4,5), (1,2), (1,2,3) );

To access:

for (int i=0; i<(num.length); i++) { for (int j=0;jAs an alternative:

For (int a: num) ( for (int i: a) ( System.out.println(i); ) )

Type variableName = new Type; Type variableName = (comma-delimited values); Type variableName = new Type; Type variableName = (comma-delimited values);

is also valid, but I prefer parentheses after the type because it's easier to see that the variable's type is actually an array.

The following shows an array declaration, but the array is not initialized:

Int myIntArray = new int;

Below is the declaration as well as the initialization of the array:

Int myIntArray = (1,2,3);

Now the following also shows the declaration as well as the initialization of the array:

Int myIntArray = new int(1,2,3);

But this third one shows the anonymous creation property of an array-object, which is indicated by the reference variable "myIntArray", so if we only write "new int(1,2,3);" then it can be an anonymous array object.

If we just write:

Int myIntArray;

This is not an array declaration, but the following statement makes the following expression complete:

MyIntArray=new int;

I find it helpful if you understand each part:

Type name = new Type;

Type is the type of a variable called name ("name" is called an identifier). The literal "Type" is the base type, and the parentheses mean it is the array type of that base. Array types, in turn, are their own, which allows you to create multidimensional arrays of type Type ( array type Type ). The new keyword refers to the allocation of memory for a new array. The number between the bracket tells how big the new array will be and how much memory will be allocated. For example, if Java knows that the underlying Type is 32 bytes and you want an array of size 5, it needs to internally allocate 32 * 5 = 160 bytes.

You can also create arrays with already existing values, such as

Int name = (1, 2, 3, 4, 5);

which not only creates empty space, but also fills it with these values. Java can tell that the primitives are integers and that there are 5 of them, so the size of the array can be determined implicitly.

Also, if you want something more dynamic, there is the List interface. This won't work, but is more flexible:

List listOfString = new ArrayList (); listOfString.add("foo"); listOfString.add("bar"); String value = listOfString.get(0); assertEquals(value, "foo");

There are two main ways to create an array:

This one, for an empty array:

Int array = new int[n]; // "n" being the number of spaces to allocate in the array

And this one, for an initialized array:

Int array = (1,2,3,4 ...);

You can also create multidimensional arrays, for example:

Int array2d = new int[x][y]; // "x" and "y" specify the dimensions int array2d = ( (1,2,3 ...), (4,5,6 ...) ...);

Take the primitive type int for example. There are several ways to declare an int array:

Int i = new int; int i = new int (value1, value2, value3, etc); int i = (value1, value2, value3, etc);

where in all these cases you can use int i instead of int i .

With reflection you can use (Type) Array.newInstance(Type.class, capacity);

Note that the method parameters... display variable arguments . Basically, any number of parameters is fine. It's easier to explain with code:

Public static void varargs(int fixed1, String fixed2, int... varargs) (...) ... varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = (100) varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = (100, 200);

Inside the method, varargs is treated like a normal int. Type... can only be used in method parameters, so int... i = new int() will not compile.

Note that when passing an int to a method (or any other Type), you cannot use the third way. In the statement int i = *(a, b, c, d, etc)*, the compiler assumes that (...) means int . But that's because you're declaring a variable. When passing an array to a method, the declaration must be either new Type or new Type (...) .

Multidimensional arrays

Multidimensional arrays are much more difficult to handle. Essentially, a 2D array is an array of arrays. int means array of int s. The key is that if an int is declared as int[x][y] , the maximum index is i . Essentially, a rectangle int is equal to:

Declaring an array of object references:

Class Animal () class Horse extends Animal ( public static void main(String args) ( /* * Array of Animal can hold Animal and Horse (all subtypes of Animal allowed) */ Animal a1 = new Animal; a1 = new Animal() ; a1 = new Horse(); /* * Array of Animal and all subtype of Horse */ Animal a2 = new Animal(); of Horse can hold only Horse and its subtype (if any) and not allowed supertype of Horse nor other subtype of Animal */ Horse h1 = new Horse; // Not allowed h1 = new Horse(); ; /* * This can not be declared. */ Horse h2 = new Animal;

An array is a sequential list of elements

Int item = value; int one_dimensional_array = ( value, value, value, .., value ); int two_dimensional_array = ( ( value, value, value, .. value ), ( value, value, value, .. value ), .. .. .. .. ( value, value, value, .. value ) );

If this is an object, then this is the same concept

Object item = new Object(); Object one_dimensional_array = ( new Object(), new Object(), .. new Object() ); Object two_dimensional_array = ( ( new Object(), new Object(), .. new Object() ), ( new Object(), new Object(), .. new Object() ), .. .. .. ( new Object(), new Object(), .. new Object() ) );

In case of objects you need to either assign it to null for initialization using new Type(..) , classes like String and Integer are special cases that will be treated as follows

String a = ("hello", "world" ); // is equivalent to String a = ( new String(("h","e","l","l","o")), new String(("w","o","r" ,"l","d")) ); Integer b = ( 1234, 5678 ); // is equivalent to Integer b = ( new Integer(1234), new Integer(5678) );

In general you can create arrays that are M dimensional

Int .. array = // ^ M times brackets ((..( // ^ M times ( bracket // this is array.. // ^ M times ))..) // ^ M times ) bracket ;

It is worth noting that creating a dimensional array M is expensive in terms of Space. Because when you create an array M with N in all dimensions, the total size of the array is greater than N^M , since each array has a link, and in M ​​dimension there is an (M -1)-dimensional array of links. The overall size is as follows

An array is a data structure that stores values ​​of the same type. An individual array element is accessed using an integer index. For example, if a is an array of integers, then the value of the expression a[i] is equal to the i-th integer in the array. An array is declared as follows: first, the type of the array is indicated, that is, the type of elements contained in the array, followed by a pair of empty square brackets, and then the name of the variable. For example, here's how to declare an array consisting of integers: int a; However, this statement only declares the variable a, without initializing it with an actual array. To create an array, you need to use the new operator. int a = new int [ 100 ] ; This operator creates an array of 100 integers. The elements of this array are numbered from 0 to 99 (not from 1 to 100). Once created, the array can be filled, for example, using a loop. int a = new int [ 100 ] ; for (int i = 0 ; i< 100 ; i++ ) a[ i] = i; //Fills the array with numbers from 0 to 99 If you try to access element a (or any other element whose index is outside the range 0 to 99) by creating an array of 100 elements, the program will terminate because an array index out of bounds exception will be thrown. range. To count the number of elements in an array, use the Arrayname.length method. For example, for (int i = 0 ; i< a. length; i++ , System. out. println (a[ i] ) ) ; После создания массива изменить его размер невозможно (хотя можно, конечно, изменять отдельные его элементы). Если в ходе выполнения программы необходимо часто изменять размер массива, лучше использовать другую структуру данных, называемую списком массивов (array list). Массив можно объявить двумя способами: int a; или int a ; Большинство программистов на языке Java предпочитают первый стиль, поскольку в нем четче отделяется тип массива int (целочисленный массив) от имени переменной.

Array initializers and unnamed arrays

Java has a facility for simultaneously creating an array and initializing it. Here is an example of such a syntactic construction: int smallPrimes = (2, 3, 5, 7, 11, 13); Note that in this case there is no need to use the new operator. In addition, you can even initialize an unnamed array: new int (16, 19, 23, 29, 31, 37) This expression allocates memory for a new array and fills it with the numbers specified in curly braces. In this case, their number is calculated and, accordingly, the size of the array is determined. This syntactic construction is convenient to use to reinitialize an array without creating a new variable. For example, the expression smallPrimes = new int (17, 19, 23, 29, 31, 37); is a shorthand version of the expression int anonymous = (17, 19, 23, 29, 31, 37); smallPrimes = anonymous; You can create an array of zero size. Such an array can be useful when writing a method that evaluates an array that turns out to be empty. A zero-length array is declared as follows: new Element type Note that such an array is not equivalent to a null object.

Copying arrays

One array can be copied to another, but both variables will refer to the same array. int luckyNumbers = smallPrimes; luckyNumbers[ 5 ] = 12 ; //Now the element smallPrimes is also 12 The result is shown in Fig. 3.1. If you need to copy all the elements of one array to another, you should use the arraycopy method from the System class. Its call looks like this: System. arraycopy (from, fromlndex, to, tolndex, count) ; The to array must be large enough to contain all the elements to be copied. Fig.3.1. Copying an array For example, the operators shown below, the results of which are shown in Fig. 3.2, create two arrays and then copy the last four elements of the first array into the second. Copying starts from the second position in the source array, and the copied elements are placed in the target array starting from the third position. int smallPrimes = (2, 3, 5, 7, 11, 13); int luckyNumbers = (1001, 1002, 1003, 1004, 1005, 1006, 1007); System. apparator(smallPrimes, 2, luckyNumbers, 3, 4); for (int i = 0 ; i< luckyNumbers. length; i++ ) System. out. println (i + ": " + luckyNumbers[ i] ) ; Выполнение этих операторов приводит к следующему результату. 0 : 1001 1 : 1002 2 : 1003 3 : 5 4 : 7 5 : 11 6 : 13 Rice. 3.2. Copying Array Elements An array in Java is significantly different from an array in C++. However, it is practically the same as a pointer to a dynamic array. This means that the operator int a = new int [ 100 ] ; //Java equivalent to operator int * = new int [ 100 ] ; //C++, not int a[ 100 ] ; //C++ In the Java language, the default operator checks the range of index changes. In addition, Java does not have pointer arithmetic—you cannot increment a pointer to access the next element of an array. Link to first

What is an array?

An array in Java is a collection of elements of the same type that can be accessed by index.

Array elements in Java are located one after another in the computer's memory. Below is an example of an array in Java.

Declaring an Array in Java

Let's declare an array to store elements of type int:

Here the variable arr is declared, which is an array. To use this variable you need to define it.

Array Definition in Java

To define an array in Java, you must specify its length, i.e. number of elements that can be stored in it:

Our array will store 5 elements.

An array is a collection of elements. Each element of the array can be referred to by its number. The number is usually called an index. The numbering of array elements in Java starts from zero.

How to load elements into an array?

Let's assign a value to the first element of the array, and the first element has index zero:

Let's assign a value to the second element of the array, and the second element has index one:

for(int inn = 0; inn< 5; inn++)
{
arr = inn;
}

When declaring an array, you can immediately load values ​​into it:

int arr = (0, 1, 2, 3, 4);

the number of elements here is 5, i.e. There is no need to specify the number of elements, it will be determined automatically.

How to get elements from an array?

Each element of the array can be referred to by its number. To get an element of an array, you need to specify the name of the array and the index of the element:

This is the first element of the array, because the first element has index zero.

Let's assign the value of the third element of the array to the variable int a:

Let's output all the elements of the array in a loop (we'll iterate over the array):

For(int inn = 0; inn< 5; inn++) { System.out.println("arr[" + inn + "] = " + arr); }

A simplified version of the loop for outputting an array is as follows:

For(int inn: arr) ( System.out.println("arr[" + inn + "] = " + arr); )

How to delete an array in Java?

You can delete an array in Java like this:

How to get the length of an array in Java?

We get the length of an array in Java like this:

int arrLength = arr.length;

How to get the first element of an array in Java?

int firstElem = arr;

How to get the half-last element of an array in Java?

int lastElem = arr;

How to define a variable length array in Java?

How to define a variable length array in Java? No way. When you define an array, you then set its length; it cannot be changed later. In such cases, collections are used, for example: Vector, ArrayList, etc.

So, the array length cannot be variable. But you can use a variable when defining an array. If so:

int cd;
int ab = new int;//Error.

then we get an error: the length of the array cannot be a variable.

You need to set the cd value:

int cd = 10;
int ab = new int;

It's okay now. If you change the cd variable after defining the array, this will not affect the array, i.e. its length will not change. Example:

Int cd = 10; int ab = new int; cd = 12;// This is possible arrLength = ab.length; System.out.println("ab array length = " + arrLength); //Outputs: ab array length = 10 ab=4;// And here is the error

We get an error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11

The maximum index of our array is 9. Changing the value of the cd variable does not affect the array, because it is already defined and its length is constant.

Variables can be used to access array elements:

Int var = 1;
int elem = arr;
var = 2;
elem = arr;

Array of characters in Java

An example of a character array in Java and its output:

Char charArr = ("S", "B", "P"); for(int inn = 0; inn< charArr.length; inn++) { System.out.println("charArr[" + inn + "] = " + charArr); }

How to fill an array in Java?

You can fill an array using the static fill method.

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. A specific element in an array is 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 specifying an index in square brackets. The numbering of array elements starts from zero. Array names are references.

A combination of declaring an array variable and allocating memory to the array directly in the declaration is possible:
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 each dimension's initializer within its own set of curly braces.
The following program creates and initializes arrays of arrays of equal length (matrices), and performs the product of one matrix by another:

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 to:
char twodi = new char; char twod2 = new char;
This alternative form of announcement is included primarily for convenience.