Tutorial

How To Use Arrays in Java

Published on April 26, 2023
    author

    toli

    How To Use Arrays in Java

    Introduction

    An array allows you to group and store multiple elements. Using an array, you can store any kind of data type—that is, a reference or primitive type. However, all the array elements must be of the same data type. The data type of the array is stated when the array is created and cannot be changed. Similarly, the length of the array—that is, how many elements it can store—is defined at the beginning and cannot be changed.

    Arrays play a fundamental role in Java as many core data types are based on them. For example, the frequently used reference type String is in fact implemented as an array of char elements. So even though you might have not known it, you have already used arrays.

    In this tutorial, you’ll use a char array to store a password securely. This is a common use case for arrays. A char array is a better choice than String for storing a password because a String object is immutable—that is, it cannot be overridden. So even though you might no longer need a password String object, you cannot just dispose of it. This means the object remains in memory, and as a result, an attacker could theoretically access this part of the memory and read the password. In contrast, you can easily override a password stored as a char array and make it unusable. Because of that, there is no chance for an attacker to learn a password from inspecting the memory.

    Prerequisites

    To follow this tutorial, you will need:

    • An environment in which you can execute Java programs to follow along with the examples. To set this up on your local machine, you will need the following:

    Creating Arrays

    To begin using an array, you have to create it first. There are a few ways to create an array, and the way you create one depends on whether you know what elements the array is going to hold.

    Info: To follow along with the example code in this tutorial, open the Java Shell tool on your local system by running the jshell command. Then you can copy, paste, or edit the examples by adding them after the jshell> prompt and pressing ENTER. To exit jshell, type /exit.

    If you don’t know the array elements, then you can create an empty array and define its size, like this:

    1. char[] password = new char[6];

    The combination [] after the char keyword defines the variable password as an array. The char keyword means that the variable holds char primitives. To create the array object, you use the new keyword with the array defined as char[6] , which means that it is an array that contains char primitives and holds six elements.

    When you run the preceding code, you will receive the following output:

    1. password ==> char[6] { '\000', '\000', '\000', '\000', '\000', '\000' }

    The output confirms that a new char array has been created under the name password. It can store six elements ([6]), which are currently empty (\000).

    Alternatively, if you already know the array elements, you can create an array called password with char elements, like this:

    1. char[] password = new char[] {'s', 'e', 'c', 'r', 'e', 't'};

    The left part of the statement, before the equals sign, is the same as the left part of statement in the first empty array example—a char array is defined under the name password. The second part of the statement, after the equal sign, starts again with the new keyword; however, the number of elements is not explicitly given. Instead, all six elements are listed. The list begins with an opening bracket, followed by the six elements. Since the elements are char primitives, they are surrounded by single quotes ('). The list ends with a closing bracket.

    When you paste the preceding code in jshell, you will get the following output:

    Output
    password ==> char[6] { 's', 'e', 'c', 'r', 'e', 't' }

    The output confirms that the password char array has been created and its elements are listed.

    In the latter example, you specified the elements while creating the array. This saved you from writing additional instructions for assigning values to the elements. That’s the benefit of creating an array this way. Alternatively, you can create code to populate the elements with each new element defined separately. You will do this next.

    Specifying and Altering Array Elements

    You will not always know the elements of an array, so specifying them, along with creating the array, might not be an option. In any case, whether you have initially specified the array elements or not, you can always specify or change them later.

    For example, you can change an element of the password array by referring to its index—that is, its place in the array—like this:

    1. password[0] = 'n';

    By using password[0], you are referring to the first element of the password array. Array elements are numbered starting at 0, so the first element will have an index of 0, as in this case. The array element index number is always specified between square brackets ([]). You redefine the array element and assign a new value to it—the 'n' char primitive.

    After you execute the preceding statement in jshell, you will get output similar to the following:

    Output
    $8 ==> 'n'

    The temporary variable $8 is used internally in jshell. It might be a different number in your case.

    There is a unique feature in jshell you can use to confirm that the password array has changed as you intended. When you paste the name of the array, in this case password, in jshell, it will print the array along with its elements without the need for additional methods:

    1. password

    You will get the following output in jshell:

    Output
    password ==> char[6] { 'n', 'e', 'c', 'r', 'e', 't' }

    This output confirms that you have successfully changed the password char array from s, e, c, r, e, t to n, e, c, r, e, t. Now, if attackers gains access to your server, they will get the altered password instead of the original one. Alternatively, if you used a String variable to store the password, the old value object will still remain in the memory for some time, even when you reassign a new value to it, and attackers could read it.

    You will continue to use the password array throughout this tutorial, so for consistency reasons, restore the value of the first element to s by referring to it again and executing the command in jshell:

    1. password[0] = 's';

    This will give an output similar to the previous one with a temporary variable , $25 in this case, which confirms the change was successful:

    Output
    $25 ==> 's'

    Once again you have the original password array with the elements 's', 'e', 'c', 'r', 'e', 't'. Now that you know how to create and alter the elements of an array, it is time to start reading and using its elements.

    Getting Array Elements

    When getting a specific array element, you will be working with its index. For example, to get the second element of the password array, you can use the following code:

    1. System.out.println(password[1]);

    In this code, you use the println() method to print the second element of the password array. (For more on the System.out.println statement, check out our tutorial How To Write Your First Program in Java.) The second element has an index of 1 because array elements are numbered starting at 0, as already mentioned.

    This code will result in the following output:

    Output
    e

    The output prints the second array element, e. Just as printing it, you could use it in any other way where a char value is suitable.

    Furthermore, you can also iterate over all the array elements using a foreach loop as explained in our tutorial How To Use Loops in Java. A loop is a structure for controlling repetitive program flow, and the foreach loop is especially useful for iterating over arrays because it requires minimum boilerplate code. Following is an example:

    1. for (char c : password) {
    2. System.out.print(c);
    3. }

    This foreach loop iterates over the password array and uses a temporary char variable called c. With each iteration, c moves from the first to the last element of the password array. Once c gets the value of the array element, you can use c in any suitable way inside the block of code. In the preceding example, you print c with the print() method.

    Notice that the print() method prints an argument without a new line. In contrast, in the tutorials so far you have used println() method which leaves a new line each time it is run. In this case, print() is more suitable since it will print all the elements from the password array on the same line and the result will be better visualized as a single word (“secret”).

    If you follow the preceding steps precisely and run this code in jshell, you will get the following output:

    Output
    secret

    If you miss the step for resetting the first array element from n back to s, you will get necret instead.

    You can get all the elements of the array when you combine the knowledge you have built so far. From this point on, you are ready to go deeper into the topic of arrays and learn useful array methods for performing various functions.

    Using Arrays Methods

    Java has a very helpful Arrays class located in the java.util package. This class helps you when working with arrays by providing you with useful methods for common use cases. This means you don’t have to reinvent the wheel and you can save yourself redundant efforts. Here are some of the most frequently used methods:

    equals() Method

    The equals() method compares two arrays to determine if they are equal. For two arrays to be equal, they must have the same length, elements, and order. Continuing with the password array example, you will create a second array called password2 containing the characters n, o, n, and e :

    1. char[] password2 = new char[] {'n', 'o', 'n', 'e'};

    Once you run this code in jshell, you will get the following confirmation:

    Output
    password2 ==> char[4] { 'n', 'o', 'n', 'e' }

    The preceding output confirms you have the password2 array. It has four elements, and they are also printed. If you haven’t exited the previous jshell session, you will also have the original password array. If you have exited your jshell session, you will have to use the steps in Creating Arrays to re-create the password array so that you have two arrays that you can compare.

    Now you can compare the two arrays, like this:

    1. System.out.println(Arrays.equals(password, password2));

    In the preceding line, you are using the println() method to print the result from the Array.equal() method comparing the password and password2 arrays.

    Since the two arrays are different, the result will be false:

    Output
    false

    The output false confirms that the two arrays are not equal. As an exercise, create other arrays and compare them. You will get a true result if two arrays are equal.

    sort() Method

    The sort() method sorts the elements of an array in ascending order. With this method, you can arrange the characters in the password array in alphabetical order by running the following:

    1. Arrays.sort(password);

    After that, you can print the array again by issuing just its name in jshell to note how it has changed, like this:

    1. password;

    The output from jshell will be:

    Output
    password ==> char[6] { 'c', 'e', 'e', 'r', 's', 't' }

    This confirms that the array still has the same elements but their order has changed. The array elements were reordered from 's', 'e', 'c', 'r', 'e', 't' to 'c', 'e', 'e', 'r', 's', 't'. It may not be a good idea to change the order of the array like this because the original order may matter. As in the case with password, if you change the order, the password is different from the original one and will not work. However, the order of the array elements may not be important in other use cases, and initial sorting might be required, as you will find out next.

    binarySearch() Method

    The binarySearch() method searches the elements of an array for a given value. One peculiarity of this method is that it requires the array elements to first be sorted; otherwise, you will get unexpected results. So once you have sorted the password array, you can find the index of an element. For example, you can find out which index the char c is in password and print it, like this:

    1. System.out.println(Arrays.binarySearch(password, 'c'));

    This will produce:

    Output
    0

    Recall that the password array is now sorted and looks like this: 'c', 'e', 'e', 'r', 's', 't'. Since the number 0 is printed, this means that the character 'c' has an index of 0 because it is the first array element.

    copyOf() Method

    The copyOf() method copies a given array to a new one when you need to increase or decrease the size of the array. Since an array’s length cannot be changed after it’s been created, you can use this method to create a new array with the required size that contains the content copied from the old array.

    For example, the password array is capable of storing only six elements, which isn’t suitable for today’s security requirements. To increase its size, you can create a new, larger array with copyOf(), like this:

    1. password = Arrays.copyOf(password, 10);

    In the preceding example, you reassign the value of password to a new array. This new array is the result of copying the old password array to a new array with a length of 10 elements. To copy it, you used the method Arrays.copyOf(), which accepts two arguments. The first argument is the array that you are copying from. The second argument is the length of the new array you are crerating.

    When you run the preceding code in jshell, you will get output similar to this:

    Output
    password ==> char[10] { 'c', 'e', 'e', 'r', 's', 't', '\000', '\000', '\000', '\000' }

    The preceding line shows that the password array has 10 elements now. The first six elements come from the original password array, which, after the alphabetical sorting, became 'c', 'e', 'e', 'r', 's', 't'. The last four values are empty because Arrays.copyOf() fills the new elements with empty values when increasing the number of elements.

    You can also verify that the new array has 10 elements by checking the length property, which every array object has. You can print this value in the usual way:

    1. System.out.println(password.length);

    Here, you use the println() method and pass password.length as an argument. The output from jshell will be:

    Output
    10

    The methods covered in this section are some of the most useful ones related to arrays. You can explore the various methods in the Arrays class further on your own following the official Arrays documentation.

    Conclusion

    In this tutorial, you used Java arrays to group related items. You learned how to create an array, how to view them, and how to use its contents. You also learned best practices and useful methods for working with arrays.

    For more on Java, check out our How To Code in Java series.

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about our products


    Tutorial Series: How To Code in Java

    Java is a mature and well-designed programming language with a wide range of uses. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).

    About the authors
    Default avatar
    toli

    author

    Still looking for an answer?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    This textbox defaults to using Markdown to format your answer.

    You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    The developer cloud

    Scale up as you grow — whether you're running one virtual machine or ten thousand.

    Get started for free

    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

    *This promotional offer applies to new accounts only.