Java Arrays: Creation and Secure Usage in Programming
Introduction: Java Arrays
Java Arrays allow you to group and store multiple elements. Using an array, you can store any kind of data type—whether it’s a reference or primitive type. However, all elements within a Java array must be of the same data type. The data type of the array is determined when the array is created and cannot be changed. Similarly, the length of the array, which defines how many elements it can store, is set at the beginning and remains fixed.
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, as 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—and therefore cannot be overridden. Even though you might no longer need a password String object, you cannot simply dispose of it, which 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 for working with Java Arrays
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:
- Java (version 11 or above) installed on your machine, with the compiler provided by the Java Development Kit (JDK). For Ubuntu and Debian, follow the steps for Option 1 in our tutorial How To Install Java with Apt on Ubuntu 22.04. For other operating systems, including Mac and Windows, follow the download options for Java installation.
- To compile and run the code examples, this tutorial uses Java Shell, which is a Read-Evaluate-Print Loop (REPL) run from the command line. To get started with JShell, check out the Introduction to JShell guide. To avoid redundant instructions, all examples are executed in one JShell session and use the same variables.
- Familiarity with Java and object-oriented programming, which you can find in our tutorial How To Write Your First Program in Java.
- An understanding of Java data types, which is discussed in our tutorial Understanding Data Types in Java.
Creating Java Arrays
To begin using an Java 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:
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:
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).
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. However, 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:
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. 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.
In jshell, you can confirm the change by pasting the array name:
password
You will get the following output:
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. If attackers gain access to your server, they will get the altered password instead. If you used a String variable, the old value would remain in memory for some time, even after reassigning a new value, making it accessible to attackers.
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:
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.
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:
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.
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:
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:
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:
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 creation, you can use this method to create a new array with the required size that contains the content from the old array.
For example, the password array can store only six elements, which isn’t sufficient for modern security needs. To increase its size, you can create a new, larger array with copyOf()
, like this:
password = Arrays.copyOf(password, 10);
In this example, you reassign the value of password
to a new array. This new array is created by copying the old password
array to a new one with 10 elements. The method Arrays.copyOf()
takes two arguments: the array to copy and the length of the new array.
Running this code in jshell produces:
Output password ==> char[10] { ‘c’, ‘e’, ‘e’, ‘r’, ‘s’, ‘t’, ‘\000’, ‘\000’, ‘\000’, ‘\000’ }
The output shows that the password array now has 10 elements. The first six come from the original password array, which, after sorting, became ‘c’, ‘e’, ‘e’, ‘r’, ‘s’, ‘t’. Arrays.copyOf()
fills the new elements with empty values, leaving the last four empty.
You can verify the new array’s size by checking the length
property:
System.out.println(password.length);
The output from jshell will be:
Output 10
Explore more methods in the Arrays
class using the official documentation.
Conclusion: Mastering Java Arrays for Efficient Data Handling
In this tutorial, you used Java arrays to group related items. You learned how to create Java arrays, how to view them, and how to use its contents. You also learned best practices and useful methods for working with arrays.