- What is an array?
- Declaring an array
- Creating an array
- Array length
- Initializing an array and accessing its elements
- Displaying an array
- Multidimensional arrays
- Useful methods for working with arrays
- A few words about what matters most
- Interesting materials about arrays
Arrays in the CodeGym course
On CodeGym, you start working with arrays on Level 7 of the Java Syntax quest. Three lessons are devoted to them, as well as 8 tasks on various levels to consolidate your skills working with arrays. But you'll encounter arrays many times during the course (in particular, the Array class will be studied in the Java Collections quest and as part of your future work. |
What is an array?
An array is a data structure that stores elements of the same type. You can think of it as a set of numbered cells. You can put some data in each cell (one data element per cell). A specific cell is accessed using its number. An element's number in the array is also called an index. In Java, an array is homogeneous, i.e. all its cells contain elements of the same type. Thus, an array of integers contains only integers (int
), an array of strings — only strings, and an array of instances of a Dog
class that we've created will contain only Dog
objects. In other words, Java won't let us put an integer in the first cell of the array, a String
in the second, and a Dog in the third. Declaring an array
How do you declare an array?
Like any variable, an array must be declared in Java. This can be done in one of two ways. They are equivalent, but the first way is more consistent with Java style. The second is a legacy of the C language: many C programmers switched to Java, and an alternate method was kept for their convenience. The table shows both ways of declaring an array in Java:No. | Declaring an array, Java syntax | Examples | Comment |
---|---|---|---|
1. | It is advisable to declare an array this way. This is Java style. | ||
2. | Array declaration method inherited from C/C++, works in Java |
dataType
is the type of the variables in the array. In the examples, we declared two arrays. One will store int
s, and the other — Object
objects. Thus, an array declration has a name and type (the type of the elements of the array). ArrayName
is the name of the array.
Creating an array
How do you create an array?
Like any other object, you can create a Java array, i.e. reserve a place in memory for it, using thenew
operator. This is how it's done:
where
typeOfArray
is the array's type and length
is its length (i.e. the number of cells) expressed as a whole number (int
). But note that here we only allocated memory for the array — we have not associated the declared array with any previously declared variable. Usually, an array is first declared and then instantiated, for example:
Here we created an array of integers called
myArray
, informing the compiler that it consists of 10 cells (each of which will contain an integer). However, it is much more common to use the following abbreviated syntax to create an array immediately when it is declared:
Please note: After an array is created using the
new
operator, its cells contain default values. For numeric types (as in our example), the default value is 0, for the boolean
type, it is false
, and for reference types, it is null
.
Thus, after executing this statement
we get an array of ten integers and, until the program does something to change the values, each cell contains 0.
You can find more information about arrays in the article "Something about arrays"
|
Array length in Java
As we said above, the length of an array is the number of elements that the array is designed to hold. The length of an array cannot be changed after it is created. Please note that array elements are numbered starting from zero in Java. Thus, if we have an array of 10 elements, then the index of the first element is 0 and the index of the last is 9. You can get the array length using thelength
variable. For example:
Output: 10
Initializing an array and accessing its elements
Now we know how to create an array in Java. The process gets us not an empty array, but an array filled with default values. For example, for anint
array, this is 0, and if we have an array of any reference type, then the default in each cell is null
.
We access an array element (for example, to set its value, display it on the screen, or perform some operation with it) by its index.
Array initialization is the process of filling an array with specific values (other than the default).
Example: let's create a string array for the 4 seasons and fill it with the names of the seasons.
Now the names of the seasons are written to the four cells of our array. We could initialize the array in a different way, combining the declaration and initialization:
What's more, the
new
operator can be omitted:
How do you display an array on the screen in Java?
You can display array elements on the screen (i.e. on the console) using afor
loop. Another, shorter way to display an array will be discussed in the paragraph entitled "Useful methods for working with arrays". In the meantime, take a look at this example where an array is displayed using a loop:
The program will display the following: Winter Spring Summer Autumn
One-dimensional and multidimensional arrays in Java
But what if we want to create not an array of numbers, strings, or other objects, but rather an array of arrays? Java lets you do this. The sort of array we are already familiar with (int[] myArray = new int[8]
) is known as a one-dimensional array. But an array of arrays is called a two-dimensional array. It's like a table that has a row number and a column number. Or, if you've learned the basics of linear algebra, you can think of it as a matrix.
Why do we need such arrays? Well, to program matrices and tables, as well as other objects that have a similar structure. For example, a chessboard can be represented by an 8x8 array.
A multidimensional array is declared and created as follows:
This array has exactly 64 elements:
myTwoDimentionalArray[0][0]
, myTwoDimentionalArray[0][1]
, myTwoDimentionalArray[1][0]
, myTwoDimentionalArray[1][1]
and so on up to myTwoDimentionalArray[8][8]
.
So if we use it to represent a chessboard, then A1 corresponds to myTwoDimentionalArray[0][0]
and E2 corresponds to myTwoDimentionalArray[4][1]
.
But how far can we push this? In Java, you can specify an array of arrays... an array of arrays of arrays, and so on. Of course, three-dimensional and higher-dimensional arrays are used very rarely. That said, you could use a three-dimensional array to program a Rubik's cube, for example.
Useful methods for working with arrays
Java has thejava.util.Arrays
class for working with arrays. In general, the most common operations performed on arrays are initialization (filling with elements), retrieving an element (by index), sorting, and searching. Searching and sorting arrays are topics for another day. On the one hand, it's good practice to write several search and sorting algorithms yourself. On the other hand, all the best algorithms have already been implemented and included in the standard Java libraries, and you can legally use them.
Here are three useful methods in this class.
Sorting an array
Thevoid sort(int[] myArray, int fromIndex, int toIndex)
method sorts an integer array or subarray in ascending order.
Searching for an element in an array
int binarySearch(int[] myArray, int fromIndex, int toIndex, int key)
. This method looks for the key
element in a sorted myArray
array or subarray, from fromIndex
to toIndex
. If the item is found, then it returns its index. Otherwise, it returns (-fromIndex)-1
.
Converting an array to a string
TheString toString(int[] myArray)
method converts to an array to a string. In Java, arrays don't override toString()
. This means that if you try to display an entire array all at once (System.out.println(myArray))
rather than one element at a time as in the paragraph entitled "Display an array on the screen", you'll get the name of the class and the array's hexadecimal hash (defined by Object.toString()
).
If you're a beginner, you may not understand the explanation about the toString
method. Initially, you don't need to, but using this method makes it easier to display an array. Java lets you easily display an array without using a loop. The example below demonstrates this.
An example using sort, binarySearch, and toString
Let's create an array of integers, display it usingtoString
, sort it using the sort
method, and then find some number in it.
Output: [I@1540e19d [1, 5, 4, 3, 7] [1, 3, 4, 5, 7] 3 -1 The first string is an attempt to display the array without using
toString
. The second is the array displayed using toString
. The third is the sorted array. The fourth is the index of the number we searched for (5) in the sorted array (remember that we count from zero, so the index of the array's fourth element is 3). In the fifth string, we see -1. This is an invalid array index. It signals that the number we searched for (in this case, 0) is not in the array.
More about methods in the Array class
Arrays class and its use — This article describes some methods in the Array class
The Arrays class has 18 important methods for working with arrays |
Arrays in a nutshell
- Essential characteristics of an array: the type of the data placed in it, its name, and its length.
The last property is determined when the array is created (when memory is allocated for the array). The first two properties are determined when the array is declared. - The array size (number of cells) must be an
int
- It is impossible to change the length of an array after it is created.
- An array element can be accessed by its index.
- Elements in arrays, like everything else in Java, are numbered starting from zero.
- After an array is created, it is filled with default values.
- Arrays in Java are not the same as array in C++. They are almost like pointers to dynamic arrays.
Useful materials about arrays
Want to know more about arrays? Check out the articles below. There include a lot of interesting and useful material on this topic.
- Something about arrays — A good detailed article about arrays
- Arrays class and its use — This article describes some methods in the
Array
class
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.