Java arrays One-dimensional and multidimensional

Lecture



As always in programming, an array is a collection of variables of the same type, stored in adjacent cells of RAM.

Arrays in the Java language refer to reference types and are described in a peculiar way, but typical of reference types. The description is made in three stages.

The first stage is the declaration. At this stage, only a variable of reference type (reference) to the array containing the type of the array is determined. For this, the name of the type of the array elements is written, in square brackets it is indicated that the reference to the array is declared, and not a simple variable, and the names of the variables of the link type are listed, for example,

double [] a, b;

Here two variables are defined - references a and b to arrays of type double. You can put square brackets and immediately after the name. This is convenient to do among the definitions of ordinary variables:

int I = 0, ar [], k = -1;

Here, two variables of integer type i and k are defined, and a reference to the integer array ag is declared.

The second stage is the definition (installation). At this stage, the number of elements of the array, called its length, is indicated , space is allocated for the array in the operational memory, and the reference variable receives the address of the array. All these actions are performed by another operation of the Java language - the new operation type, allocating a section in RAM for an object of the type specified in the operation and returning the address of this section as a result. For example,

a = new double [5];

b = new double [100];

ar = new int [50];

Array indices always begin with fr. The array a consists of five variables a [0], and [1],, and [4]. There is no element a [5] in the array. Indices can be specified by any integer expressions, except for the long type, for example, a [i + j], a [i% 5], a [++ i]. The Java runtime system ensures that the values ​​of these expressions do not exceed the bounds of the array length.

The third stage is initialization . At this stage, the array elements get the initial values. For example,

a [0] = 0.01; a [1] = -3.4; a [2] = 2: .89; a [3] = 4.5; a [4] = -6.7;

for (int i = 0; i <100; i ++) b [i] = 1.0 / i;

for (int i = 0; i <50; i ++) ar [i] = 2 * i + 1;

The first two stages can be combined:

doublet] a = new double [5], b = new double [100];

int i = 0, ar [] = new int [50], k = -1;

You can immediately set the initial values ​​by writing them in braces separated by commas in the form of constants or constant expressions. Moreover, it is not even necessary to indicate the number of elements in the array; it will be equal to the number of initial values;

double [] a = {0.01, -3.4, 2.89, 4.5, -6.7};

You can combine the second and third stage:

a = new doublet] {0.1, 0.2, -0.3, 0.45, -0.02};

You can even create a nameless array, immediately using the result of the new operation, for example, like this:

System.out.println (new char [] {'H', 'e', ​​'1', '1', 'o'});

The array reference is not part of the described array, it can be transferred to another array of the same type by an assignment operation. For example, after assigning a = b both references a and b point to the same array of 100 real variables of type double and contain the same address.

A link can assign an "empty" null value that does not indicate any memory address:

ar = null;

After that, the array pointed to by this link is lost if there are no other links to it.

In addition to the simple assignment operation, with links one can make only comparisons for equality, for example, a = b, and inequality, and! = B. At the same time, the addresses contained in the links are matched; we can find out if they refer to the same array.

Specialist Note

Arrays in Java are always dynamically defined, although references to them are statically defined.

In addition to the array reference, an integer constant with the same name length is automatically determined for each array. It is equal to the length of the array. For each array, the name of this constant is specified by the name of the array through a dot. So, after our definitions, the constant a.length is equal to 5, the constant b. The length is 100, a ar. length is 50.

The last element of array a can be written like this: a [a. length - 1], the last but one - a [a. length - 2], and so on. The elements of an array are usually iterated in a loop of the form:

double aMin = a [0], aMax = aMin;

for (int i = 1; i

if

if (a [i]> aMax) aMax = a [i];

}

double range = aMax - aMin;

Here the range of values ​​of the array is calculated.

The elements of the array are ordinary variables of their type, with them you can perform all operations that are valid for this type:

(a [2] + a [4]) / a [0], etc.

Connoisseurs C / C ++

An array of characters in Java is not a string, even if it ends with the null character '\ uOOOO'.

Multidimensional arrays

Array elements in Java can be arrays again. You can declare:

charf] [] s;

which is equivalent to

chart] with [];

or

char with [] [];

Then we define the external array:

c = new char [3] [];

It becomes clear that c is an array consisting of three array elements. Now we define its array elements:

with [0] = new char [2];

with [1] = new char [4];

with [2] = new char [3];

After these definitions, the variable c. Length is equal to 3, with [0]. Length is 2,

c [l] .length is 4 and with [2.length is 3.

Finally, we set the initial values ​​with [0] [0] = 'a', with [0] [1] = 'r',

with [1] [0] = 'g', with [1] [1] = 'a', with [1] [2] = 'y', etc.

Comment

A two-dimensional array in Java does not need to be rectangular.

Descriptions can be abbreviated:

int [] [] d = new int [3] [4];

And set the initial values ​​as follows:

int [] [] inds = {{I, 2, 3}, {4, 5, 6}};

Listing 1.6 shows an example of a program that calculates the first 10 lines of Pascal's triangle, which enters them into a triangular array and displays its elements on the screen. Fig. 1.4 shows the output of this program.

Listing 1.6. Pascal's Triangle

class PascalTriangle {

public static final int LINES = 10; // So defined constant

public static void main (String [] args) {

int [] [] p, = new int [LINES] [];

p [0] = new int [1];

System, out. println (p [0] [0] = 1);

p [l] = new int [2];

p [l] [0] = p [l] [1] = 1;

System.out.println (p [1] [0] + "" + p [l] [l]);

for (int i = 2; i

p [i] = new int [i + l];

System.out.print ((p [i] [0] = 1) + "");

for (int j = 1; j

System.out. print ((p [i] [j] = p [il] [jl] -bp [il] [j]) + "");

System, out. println (p [i] [i] = 1)

}

}

}

Java arrays One-dimensional and multidimensional

Fig. 1.4. The degenerate of Pascal's triangle in the window-Gomrriand - Prompt


Comments

Ольга
13-11-2022
Здравствуйте.Пітаюсь реализовать процесс решения системы трех линий уравнений с тремя неизвестными по методу Крамера (https://www.mathros.net.ua/rozvjazok-systemy-linijnyh-algebraichnyh-rivnjan-metodom-kramera.html).С массивами пока не очень разбираюсь, поэтому проблема возникает при формировании вспомогательных определителей. Если вам не трудно, помогите с этим фрагментом кода.

To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Object oriented programming

Terms: Object oriented programming