Java Array. Arrays in Java. Java for beginners

Table of contents:

Java Array. Arrays in Java. Java for beginners
Java Array. Arrays in Java. Java for beginners
Anonim

An array is a powerful tool that allows you to work with large amounts of data. Obviously, if you need to store, for example, 100 values somewhere in the course of your code, then making the same number of variables for this is at least unreasonable. An array allows you to store a large number of values under one name and access them by the appropriate index. The concept of arrays is the cornerstone in learning Java for beginners. After all, they are the basis for many data structures.

Because Java is primarily OOP, compared to arrays in other programming languages, java array has one distinctive feature - they are represented as objects. Among other benefits, this eliminates the need to keep track of memory cleanup as it is freed automatically.

Creating and manipulating one-dimensional arrays

A one-dimensional array is a classic Java array and is a collection of elements linked by a common name, each of which corresponds to a certain index. The way to declare an array is shown in the figurebelow.

java array
java array

First, the Java array type is declared, which defines the type of values stored in it. It can be any valid data type in Java. This is followed by the name of the array and square brackets telling the compiler that the variable is an array. Pay attention to an important fact. Square brackets can be placed after the base type of an array or after an array name. After the equal sign, the new operator is indicated, which initiates the allocation of memory for the array (same as in the case of objects), the type of elements that will be stored in it (must be compatible with the base type declared earlier), and, finally, their number, indicated in square brackets.

The numbering of elements in a Java array starts from 0. Thus, the index of the first element in this array will be 0, and the sixth element will be 5. square brackets next to the name. Thus, you can both assign a value to an element and retrieve it. However, you should be careful, because if you pass an index at which there is no element, an error will occur.

Multidimensional arrays in Java

Multidimensional arrays are series of one-dimensional arrays referenced by elements of other arrays. In other words, they are arrays of arrays. The simplest among them are two-dimensional. On their example, we will try to understand the concept. For clarity, the figure below shows the syntax and diagram that describes the structure of a two-dimensional array.

arrays in java
arrays in java

As you can see, the syntax is not very different from one-dimensional arrays. Let's take a look at the structure. In the first brackets, we have allocated space for 5 elements. These elements are nothing more than references to individual arrays. The size of each of them is determined by the number in the second brackets. In fact, matrices are analogous to two-dimensional arrays in mathematics. Please note that in addition to the elements, a separate place is allocated in memory where the value of the array length (length) is stored. As a rule, work with multidimensional arrays is carried out through nested for loops.

java for beginners
java for beginners

Irregular arrays

A two-dimensional array is an array of arrays. This we have already found out. But can the arrays it contains have different lengths? The answer is yes, they can. To do this, Java provides the ability to declare a two-dimensional array in a special way. For example, we want to create a two-dimensional array that would store three one-dimensional arrays of length 2, 3, and 4, respectively. It is declared as follows:

intarr=newint[3];

Note that we didn't include the number in the second brackets. Determining the size of arrays in arr is done like this:

arr[0]=new int[2];

arr[1]=new int[3];

arr[2]=newint[4];

When referring to the element at index 0, which points to the first array, we declare it with a dimension of 2. The element at index 1 will store an array of dimension 3, and so on. It's pretty simple.

Alternate declaration syntaxjava array

Arrays can also be initialized directly when they are created. It's pretty simple.

array java class
array java class

Notice the declaration of jerseyNumber and playerName arrays.

In the case of two-dimensional arrays, this declaration looks like this:

int arr={

{1, 2, 3}, {4, 5, 6}, {7, 8, 9}

}

To do this, instead of the new operator, curly braces are opened, in which all elements are listed separated by commas. Java in this case automatically allocates memory for them and indexes them accordingly.

Helper class Arrays

To work with things like arrays in Java, the java.util package provides a special Arrays class that provides many static methods that make operations with them much easier. A list of the main methods is shown in the figure below.

java array methods
java array methods

Let's explore some of the most useful Java array methods:

- copyOf (array, length) – returns a copy of the passed array of the corresponding length. If the passed length is greater than the original array, then all "extra" elements are filled with a default value (0 if a simple type, and null if a reference type).

- copyOfRange(array, first index, last index) - not shown in the figure, but useful method. It copies the portion of the passed array, defined by the corresponding indexes, starting with the first and ending with the last.

- sort (array) - sorts the elements of an array byascending.

- fill (array, value) – fills the given array with the corresponding value.

- binarySearch (array, value) - returns the index under which the element with the corresponding value is located in the passed sorted array. If there is no such element, then a negative number is returned.

Because the methods are static, there is no need to create an instance of the Arrays class to call them. They are called directly from it: Arrays.sort(arr).

Conclusion

We've covered the most important aspects of arrays, and for those who are just starting to learn Java for beginners, this is enough for a basic understanding of such an entity as an array and the basic techniques for working with it. Of course, practice will give a better understanding of how this tool works. Therefore, do not be lazy to do some exercises, manipulating arrays in various ways.

The Array Java helper class is already used in "combat" conditions, so it is recommended to learn how to perform all basic operations with arrays manually.

Popular topic

Editor's choice

  • Windows 7 password bypass: possible methods and recommendations from experts
    Windows 7 password bypass: possible methods and recommendations from experts

    The fact that users (most often computer administrators) protect Windows operating systems from unauthorized use, for example, in their absence at the computer, does not surprise anyone. However, often the administrator may not give the registered user enough rights to perform any actions or set personal settings, and therefore it may be necessary to log in with an administrator registration

  • How to remove a virus from a flash drive without losing data?
    How to remove a virus from a flash drive without losing data?

    Removable USB storage devices in the form of the most common flash drives are susceptible to viruses no less than hard drives with operating systems installed on them. And it is often quite problematic to identify the presence of such a threat or neutralize it. How to remove a virus from a flash drive and restore files (hidden or infected) will be discussed further

  • File viruses are computer code to achieve goals bypassing security systems
    File viruses are computer code to achieve goals bypassing security systems

    File viruses are computer code to achieve goals bypassing security systems. This is what inspired people to create antiviruses, what allows hackers to learn and steal millions of dollars every day

  • PC prevention for stable operation - expert advice. Computer help
    PC prevention for stable operation - expert advice. Computer help

    The fact that almost all modern computer systems require constant care, apparently, all users know. But not everyone has a clear enough idea of what this should manifest itself in. To keep the computer, operating system and installed applications in the most efficient condition, it is necessary to carry out preventive maintenance of the PC software and monitor the hardware components (installed equipment)

  • Detector software: what is it in the field of anti-virus protection?
    Detector software: what is it in the field of anti-virus protection?

    Apparently, many users of modern computer systems have heard or know that there are so-called detector programs. What they are is easy to understand if you just turn to the translation or interpretation of the English word detect, which literally means “to detect”