# The Java Tutorial: Arrays

EDIT

We've already covered primitive data types in Java. It's now time to look at the Array object.

## What is an array in Java?

An array is a container object. It holds a fixed number of values of a single type. An array's size is set when it's' initialized. An array's size does not change.

### Basic example of an array in Java

``public class MyClass {    public static void main(String args[]) {        char[] myArray = new char;        myArray = 'a';        myArray = 'b';        myArray = 'c';        myArray = 'd';        myArray = 'e';        System.out.println(myArray);        //prints d    }}``

#### Creating Arrays

In this example, we've set a variable myArray to a new array with 5 char elements. Notice how we specify both the type of element char and size . This means our myArray array will hold 5 elements of the char data type.

As an alternative, we could have initialized the same array like this:

``char[] myArray = {'a', 'b', 'c', 'd', 'e'};``

#### Assigning elements to an array

In the first example, notice how we set the first element in myArray.

``myArray = 'a';``

This assigns a value 'a' to the first element in the array. Elements in an array are stored in a specific order. This means each element has a corresponding index position that you can access it by. Notice how we access the 4th element in the array:

``myArray//returns the 4th element in the array``

This reads the element at position 3 (or the 4th element) in the array, in this case 'd'.

#### Why is the first element 0 and not 1?

To access the first element in an array, we start at position 0. This means the second element is at position 1, the third at position 2, etc. This is called zero-based indexing meaning the position is simply an offset from the beginning of the array.

### Multidimensional arrays in Java

You can create arrays of arrays in Java...

``public class MyClass {    public static void main(String args[]) {        char[][] myArray = {                {'a','b','c','d'},                {'e','f','g'}        };        System.out.println(myArray);        //prints g    }}``

Notice how we add an additional [] to signify a multidimensional array. We access a specific element in the array via myArray. This returns the third element of the second element of myArray.

### Using the java.util.Arrays class

Java provides some methods out of the box for working with arrays. Using the java.utils.Arrays class, you can perform searches, sorting, copying, etc. of arrays. The following are examples of using some of the most popular methods in java.utils.Arrays:

#### Copy an array

``import java.util.Arrays;public class MyClass {    public static void main(String args[]) {        char[] myArray = {'a','b','c','d'};        char[] copyArray = Arrays.copyOfRange(myArray, 1, 3);        System.out.println(copyArray);        //prints bc    }}``

Notice how we make use of the Arrays.copyOfRange() method to return a copy of the original myArray array. You'll notice this method takes three parameters. The first parameter is the source array, in this case myArray. The second parameter is the initial index of the range to be copied (inclusive), in this case 'b'. The third parameter is the final index of the range to be copied (exclusive).

#### inclusive vs exclusive

Given the range 1-5 inclusive, we get (1,2,3,4,5). Given the same range exclusive, we get (1,2,3,4). In our previous example, the copyOfRange() method accepts an exclusive position as its third parameter.

The System class has a similar arraycopy() method however the Arrays.copyOfRange() is generally preferred because it doesn't require the preexistence of a second array and simply returns the copied result.

#### Search an array

Using binary search, you can search an array for a specific value. For example:

``import java.util.Arrays;public class MyClass {    public static void main(String args[]) {        char[] myArray = {'a','b','c','d'};        int position = Arrays.binarySearch(myArray, 'c');        System.out.println(position);        //prints 2    }}``

In this example, we use the Arrays.binarySearch() method to search myArray for the value 'c'. Notice how the method returns an integer being the position of the first occurrence of 'c' in myArray.

This method optionally supports another parameter specifying an end index. This allows you to search for a value within a given range.

#### Compare array equality

Two arrays are considered equal if they contain the same elements in the same order.

``import java.util.Arrays;public class MyClass {    public static void main(String args[]) {        char[] array1 = {'a','b','c','d'};        char[] array2 = {'a','b','c','d'};        char[] array3 = {'a','c','d','b'};        System.out.println(Arrays.equals(array1, array2));        //prints true        System.out.println(Arrays.equals(array1, array3));        //prints false    }}``

Notice how we use the Arrays.equals() method to see if any two given arrays are equal. Remember that arrays are equal if they contain the same number of elements in the same order. Although array1 and array3 have the same length, they don't have the same elements. For this reason, they are not considered equal. Since array1 and array2 have the same elements in the same order, they are equal.

#### Sorting an array

You can sort an array of integers using the Arrays.sort() method:

``import java.util.Arrays;public class MyClass {    public static void main(String args[]) {        int[] myArray = {33,55,23,64,2};        Arrays.sort(myArray);        System.out.println(myArray);        //prints 2    }}``

Notice how we call Arrays.sort() to sort myArray in ascending order. After calling the sort method on myArray, the first element at position 0 is now 2.

The Arrays.sort() method can also be used to sort strings in alphabetical order, sort sub arrays, and sort based on custom logic.

## Conclusion

Java arrays are collections of elements having the same type. An array's size is fixed when it's initialized. Arrays are good for storing collections of elements where order matters. Every element stored in an array has a corresponding index. You can access and modify an array's elements based on their position within the array.
{"ft_lang_label":"__label__en","ft_lang_prob":0.7106343,"math_prob":0.78609693,"size":5910,"snap":"2022-27-2022-33","text_gpt3_token_len":1405,"char_repetition_ratio":0.15899086,"word_repetition_ratio":0.08492569,"special_character_ratio":0.25617597,"punctuation_ratio":0.16292602,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9876986,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-07-05T18:44:57Z\",\"WARC-Record-ID\":\"<urn:uuid:28904ca4-90e2-4375-8b90-8294603267d1>\",\"Content-Length\":\"1049429\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:430dc571-3a6c-4bb2-9aa9-a0476105f07e>\",\"WARC-Concurrent-To\":\"<urn:uuid:1e96279f-e72c-4b6a-9c47-1888b167f250>\",\"WARC-IP-Address\":\"44.229.210.148\",\"WARC-Target-URI\":\"https://www.stackchief.com/tutorials/The%20Java%20Tutorial%3A%20Arrays\",\"WARC-Payload-Digest\":\"sha1:FR3IYQGZLLPOAIPLB45OKQ44CC2NPN2N\",\"WARC-Block-Digest\":\"sha1:3SODFZ2K3P3PJXETAMXN35I53RSFSH2I\",\"WARC-Truncated\":\"length\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-27/CC-MAIN-2022-27_segments_1656104597905.85_warc_CC-MAIN-20220705174927-20220705204927-00261.warc.gz\"}"}