The book "Java for all"

image Hello, habrozhiteli! This book is intended for beginners.







For many years, the Java language has been one of the most popular and sought after. It is beautiful, effective and, most importantly, very productive. But, unfortunately, not the easiest. That is why the demand for Java programmers is consistently high. The Java language is a diamond that will adorn the baggage of knowledge of any programmer. And learning Java, as I hope, readers of this book will have to make sure, is not only useful, but also interesting. The basis of the book is lecture courses, at different times, which I read for the masters of the Faculty of Physics of Kiev National University named after Tarasa Shevchenko, bachelors of the medical-engineering faculty of the National Technical University of Ukraine “Kiev Polytechnic Institute” and students of various programming courses. The material of the book and the way of presentation are adapted for everyone who wants to learn Java not only in educational institutions, but also independently. Therefore, the book can be used as a tutorial.







Arrays



An array means a set of the same type of values ​​(variables), which can be accessed by a common name. This chapter is devoted to arrays.







Variables belonging to one array are called elements of this array. To uniquely identify an element of an array, you need to know the name of the array and the position (placement) of the element in the array. The position of the elements in the array is determined using integer indices. The number of indices needed to identify an element of an array is called the dimension of the array. A one-dimensional array is an array in which elements are identified using a single index.







One-dimensional arrays



It is convenient to imagine a one-dimensional array as an ordered chain or sequence of variables (of the same type). To declare a one-dimensional array, you must specify the type to which the elements of the array belong, the name of the array, and also the number of elements included in the array. The syntax for declaring a one-dimensional array is:







[] =new [];
      
      





First, the type of the elements of the array is indicated, and after the type identifier, empty square brackets follow. Next, the name of the array, the assignment operator, the instruction (operator) new, again the type of the elements of the array and in square brackets the size of the array (the number of elements in the array). For example, the int nums = new int [20] command declares an integer nums array of 20 elements.







Strictly speaking, the array declaration command presented here is a symbiosis of two commands: the int [] nums command, the declaration of the nums variable of the integer array type (array variable), and the new int [20] instruction, which, in fact, creates the array. This instruction is assigned the value of the nums variable, and as a result of the array reference, it is written to the nums variable. In other words, the process of creating an array can be performed with two commands:







 int[] nums; nums=new int[20];
      
      





Moreover, these commands can be posted in the program code - that is, we can declare an array variable and only then, in another place in the code, create an array (and write a link to this array in the array variable).







DETAILS Previously, we mainly dealt with basic, or primitive, types (such as int, char or double). A variable of the base type stores the value. Technically, it looks like this: a space is allocated for a variable in memory, and the value of the variable is written to this place. But there is another way of working with data in which a variable refers to data. This is what happens with objects, and so arrays are implemented. There is actually an array, but we get access to it not directly, but with the help of an intermediary, which is an array variable. The value of the array variable is not the array, but the address of the array. Therefore, creating an array variable does not mean creating an array. An array is created separately. We will describe this situation as one in which the array variable refers to the array. Each time we need to access the array, we will access the array variable that refers to the given array.

Although at first glance such a scheme may seem redundant, nevertheless, it has its advantages. And we will see this.

In cases where there is no misunderstanding, we will identify the array variable with the array.







When declaring an array variable, it is allowed to indicate square brackets either after the type identifier or after the array name. For example, instead of the int [] nums command, you can use the int nums [] command.







An element of a one-dimensional array is accessed through the name of the array with the index of the element indicated in square brackets. Indexing array elements starts from zero. Thus, the reference to the first element of the nums array will look like nums [0]. If there are 20 elements in the array, then the last element of the array has an index of 19, that is, the instruction to access the element looks like nums [19].







The length of the array can be found using the length property: the name of the array is indicated and, through the dot, the length property. For example, to find out the length of the nums array, you can use the nums.length statement. Then a reference to the last element of the array can be written as nums [nums.length-1].







NOTICE Java uses an automatic check to see if the array is out of bounds. Therefore, if the code refers to a nonexistent array element, an error occurs.

When declaring an array, memory is allocated for it. In Java, array elements are automatically initialized with zero values ​​- the selected cells are zeroed, and the values ​​of these zeroed cells are interpreted depending on the type of array. But you should not rely on such automatic initialization. It is wise to initialize the elements of the array explicitly. To do this, use the loop operator or specify a list of element values ​​when declaring an array.







To initialize an array with a list of values ​​when declaring an array variable, after it is indicated (through the assignment operator) a list of values ​​enclosed in braces. For example:







 int[] data={3,8,1,7};
      
      





Here, the variable data is declared for the integer array, an array is created, and a link to it is written to this variable. The size of the array and the values ​​of the elements are determined automatically according to the number of elements in the list of values. In this case, an integer array of four elements is created with the values ​​of the elements 3, 8, 1 and 7. The same result can be achieved using, for example, the following commands:







 int[] data; data=new int[]{3,8,1,7};
      
      





The first int [] data command declares an array variable. The instruction new int [] {3,8,1,7} creates an array of four integers, and a reference to this array is assigned to the variable data (meaning the command data = new int [] {3,8,1,7}) .

An example of declaring, initializing, and using arrays is shown in Listing 3.1.







Listing 3.1. Introducing One-Dimensional Arrays



 class Demo{ public static void main(String[] args){ //  : int i,n; //   : int[] data; //  : data=new int[]{3,8,1,7}; //  : n=data.length; //  : int[] nums=new int[n]; //   : for(i=0;i<nums.length;i++){ nums[i]=2*data[i]-3; System.out.println("nums["+i+"]="+nums[i]); } } }
      
      





The program declares and initializes a data array of four elements. The length of the array is calculated by the data.length statement. This value is written to the integer variable n (command n = data.length). Next, the int [] nums = new int [n] command declares another integer nums array. The number of elements in this array is determined by the value of the variable n, therefore, it coincides with the size of the data array. Filling the nums array is done using a loop statement. The values ​​of the elements of the nums array are calculated based on the values ​​of the elements of the data array (command nums [i] = 2 * data [i] -3). To display the values ​​of the elements of the nums array, use the System.out.println command ("nums [" + i + "] =" + nums [i]).







The following shows what the result of program execution looks like:

The result of the program (from Listing 3.1)







 nums[0]=3 nums[1]=13 nums[2]=-1 nums[3]=11
      
      





Once again, we note that the indexing of array elements starts from zero. Therefore, in the loop operator, the index variable i is initialized with the initial zero value, and the strict inequality operator is used in the test condition i <nums.length.

It is also important that when creating the nums array, its size is determined using the variable n, the value of which is calculated during the execution of the program.







Two-dimensional and multidimensional arrays



The dimension of the array may be greater than one. But in practice, arrays of dimension higher than the second are rarely used. Next, we look at ways to declare, initialize, and use two-dimensional arrays in which an access to an element of an array is performed using two indices. If you represent a two-dimensional array as a table, then the first index of the element determines the row in which the element is located, and the second index determines the column in which the element is located.







DETAILS Although a two-dimensional array is conveniently represented as a table, it is implemented in a completely different way. In fact, a two-dimensional array in Java is a one-dimensional array whose elements are array variables. Each such variable refers to a one-dimensional array. When using this design, the illusion arises that we are dealing with a table.

Creating two-dimensional arrays is as simple as creating one-dimensional arrays. But when declaring a variable for a two-dimensional array, two pairs of empty square brackets are indicated after the type identifier, and the instruction for creating a two-dimensional array — in separate square brackets — indicates the size for each of the indices (the number of rows and columns in the array). The syntax for declaring a two-dimensional array is as follows:







 [][] =new [][];
      
      





As in the case of a one-dimensional array, this command can be divided into two:







 [][] ; =new [][];
      
      





The first command declares a variable for a two-dimensional array. The second command creates an actual two-dimensional array with the specified sizes, and a reference to this array is assigned as the value of the array variable. For example, the double [] [] data = new double [3] [4] command creates a two-dimensional array with elements of the double type. The array has 3 rows and 4 columns, and the link to the array is written to the data variable. The same commands will result in the same result:







 double[][] data; data=new double[3][4];
      
      





Access to the elements of a two-dimensional array is performed in the following format: the name of the array is indicated, in square brackets is the first index of the element, in other square brackets is the second index of the array element. Indexing across all dimensions starts from scratch. For example, the data [0] [3] link is a call to an element of the data array with indices 0 and 3, and it is an element in the first row and fourth column.







To initialize a two-dimensional array, nested loop operators or a list consisting of lists of values ​​are used. Each such internal list defines the values ​​of the array elements in a string. The following are examples of initializing a two-dimensional array using a list:







 double[][] data={{0.1,0.2,0.3},{0.4,0.5,0.6}}; int nums[][]={{1,2,3},{4,5}};
      
      





The first command creates and initializes a 2 by 3 two-dimensional data array (two rows and three columns). The number of lines is determined by the number of elements in the external list. There are two such elements - these are the lists {0.1,0.2,0.3} and {0.4,0.5,0.6}. Each of these lists has three elements. From here we get an array of size 2 by 3. The list {0.1,0.2,0.3} defines the values ​​of the elements in the first line, the list {0.4,0.5,0.6} determines the values ​​of the elements in the second line. For example, the data [0] [0] element gets the value 0.1, the data [0] [2] element gets the value 0.3, the data [1] [0] element gets the value 0.4, and the data [1] [2] element gets the value 0.6 .







The second command creates an integer nums array, which consists of two lines (since there are two elements inside the assigned list - lists {1,2,3} and {4,5}). However, the first line of the created array contains three elements (since the list contains {1,2,3} three values), and the second line of the array contains two elements (since the list {4,5} has two values). In the created array, the nums [0] [0] element has the value 1, the nums [0] [1] element has the value 2, the nums [0] [2] element has the value 3, the nums [1] [0] element has the value 4 , and the element nums [1] [1] is the value 5.







DETAILS The problem is that the nums array in different lines contains a different number of elements, no. Technically, everything is implemented more than simply. The variable of a two-dimensional array nums actually refers to a one-dimensional array of two elements (the number of rows in a two-dimensional array). But the elements of this array are not integers, but variables that can refer to one-dimensional integer arrays (relatively speaking, the elements are of type int []). The first variable refers to a one-dimensional array of three elements (1, 2 and 3), and the second variable refers to a one-dimensional array of two elements (4 and 5). When we index (with a single index!) The nums variable, we get access to the element of the one-dimensional array that this variable refers to. For example, nums [0] is the first element, and nums [1] is the second element of the mentioned array from array variables. And these elements are references to arrays. They can be indexed. Therefore, let's say nums [0] [1] is the second element in the array referenced by the first element nums [0] in the array referenced by the nums variable. So everything really happens. And we interpret the nums [0] [1] instruction as an appeal to an element in the first row and in the second column of a two-dimensional array.

Listing 3.2 shows an example of a program that creates a two-dimensional array that is populated using nested loop statements.







Listing 3.2. Create a two-dimensional array



 class Demo{ public static void main(String[] args){ int i,j,n=3,val=1; //   : int[][] nums=new int[n-1][n]; //   : for(i=0;i<n-1;i++){ //    for(j=0;j<n;j++){ //    //   : nums[i][j]=val++; //   : System.out.print(nums[i][j]+" "); } //    : System.out.println(); } } }
      
      





The int [] [] nums = new int [n-1] [n] command creates an integer nums array with n-1 rows and n columns. The variable n is preliminarily assigned the value 3. The array is filled using nested loop operators. The value of the array element (for given indices i and j) is assigned by the command nums [i] [j] = val ++. Here, the nums [i] [j] element is assigned the current value of the variable val, and immediately after that the value of the variable val is increased by one.







NOTICE As a result of executing the val ++ instruction, the value of the variable val is increased by one. But since the postfix form of the increment operator is used, the value of the expression val ++ is the old (before increasing by one) value of the variable val.

After calculating the element value, it is displayed in the output area. As a result of the program, we get:

The result of the program (from listing 3.2)







 1 2 3 4 5 6
      
      





Listing 3.3 shows the code for a program that creates a two-dimensional array with strings of different lengths.







Listing 3.3. Array with strings of different lengths



 class Demo{ public static void main(String[] args){ int i,j,val=1; //   (   ): int[][] nums=new int[4][]; //     : for(i=0;i<nums.length;i++){ //    : nums[i]=new int[i+1]; } //  : for(i=0;i<nums.length;i++){ for(j=0;j<nums[i].length;j++){ //   : nums[i][j]=val++; //   : System.out.print(nums[i][j]+" "); } //    : System.out.println(); } } }
      
      





The int [] [] nums = new int [4] [] command creates a two-dimensional integer nums array. This array consists of four rows. However, the size of the lines is not specified - the second pair of square brackets at the end of the command is empty. More precisely, there are no lines yet. They need to be created. Lines are created in the loop statement. In this loop statement, the index variable i runs through values ​​from 0 to nums.length-1, inclusive. The nums [i] = new int [i + 1] command creates a row of a two-dimensional array with index i. Such a line contains i + 1 element.







DETAILS Technically, everything happens as follows: the new int [i + 1] instruction creates a one-dimensional array (a string for a two-dimensional array) and a reference to this array is written to the nums [i] variable. At the same time, nums [i] can be interpreted as a link to a line with index i. The meaning of the nums.length instruction will become clear if we recall that in fact a two-dimensional array is a one-dimensional array, whose elements refer to one-dimensional arrays. In this case, nums.length gives a value for the number of elements in the array referenced by the nums variable - that is, this is the number of rows in the two-dimensional array.

As a result, we get a two-dimensional array of a triangular type: in the first line of the array there is one element, in the second - two elements, and so on, up to the fourth line of the array.

The created array is filled using nested loop operators. The index variable i in the external loop operator takes values ​​from 0 to nums.length-1 and defines a row in the two-dimensional nums array. For the index variable j, the upper limit of the range of variation is determined by the nums [i] .length instruction, which returns the number of elements in the row with index i (the j variable changes from 0 to nums [i] .length-1 inclusive).







DETAILS It should be noted that nums [i], in fact, is a variable that refers to a one-dimensional array forming a row with index i. The number of elements in this array (string) is determined by the expression nums [i] .length.

The value of the array elements is assigned by the command nums [i] [j] = val ++. The following shows what the result of program execution looks like:

The result of the program (from listing 3.3)







 1 2 3 4 5 6 7 8 9 10
      
      





As expected, we got an array with different numbers of elements in different lines.







NOTICE Arrays whose dimension is greater than two are created in the same way. When declaring a variable for a multidimensional array, pairs of empty brackets are indicated after the type identifier. The number of such pairs is determined by the dimension of the array. In the array creation command, the size of each index is indicated in separate square brackets.

»More details on the book can be found on the publisher’s website

» Contents

» Excerpt







25% off coupon for hawkers - Java







Upon payment of the paper version of the book, an electronic book is sent by e-mail.








All Articles