Home

 › 

Articles

 › 

Arrays In Java Explained With Examples

Arrays in Java

Arrays In Java Explained With Examples

Arrays in Java, just like in other programming languages, are an incredibly useful tool for programmers to manage and process large amounts of data efficiently. If you’ve ever wondered how large amounts of data are organized and processed behind the scenes, arrays are likely the key to that.

If you’re just setting out to be a Java developer, wrapping your head around such abstract concepts can seem to be a bit of a head-scratcher. Don’t sweat it, though, as they’re no doubt a fundamental part of programming in Java, and mastering them will make you a better programmer overall. Not to mention that they’re really not that difficult to understand.

By the end of this article, you’ll have a solid understanding of arrays and be well on your way to becoming proficient in Java. Let’s start by first understanding the concept of an array in programming.

What Exactly Is an Array?

An array is a collection of data items, all of the same type, stored in a contiguous block of memory under a single variable name. Think of it as a container that can hold multiple values of the same kind, such as integers, strings, or even other objects. 

Each value in an array is assigned a unique index or key, which is used to access and manipulate the value. The key allows the programmer to easily access a specific value in the array without having to search through the entire collection. 

In its most basic form in Java, arrays store multiple values of the same data type, and the elements in an array are accessed using an index — the key.

The index of the first element in an array is always 0, and the index of the last element is always the length of the array minus one. Arrays can be one-dimensional or multi-dimensional, and they can hold primitive data types or objects. 

How to Declare/Initialize an Array in Java

To declare an array, you must first specify the data type of the elements that will be stored in the array. For example, to declare an integer array, you would use the following syntax:

int[] numbers;

This declares an integer array called “numbers.” However, to initialize or instantiate the array, you must specify the type and number of elements it will hold:

numbers = new int[5];

This initializes the “numbers” array to hold five integer values. You can also initialize an array with values using the following syntax if the elements are known:

int[] numbers = {1, 2, 3, 4, 5};

This initializes the “numbers” array with the values 1, 2, 3, 4, and 5. You can also use a loop to initialize an array:  

int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i + 1;
}

This initializes the “numbers” array with the values 1, 2, 3, 4, and 5. Note that the time complexity of this initialization method is O(n).

Accessing and Manipulating Array Elements

Arrays in Java allow you to access and manipulate elements using indexes. Indexing starts at 0, which means the first element in an array has an index of 0, the second element has an index of 1, and so on.

To access an element in an array, you can use the square bracket notation to specify the index. For instance, if you have an array of integers named “numbers”, and you want to access the third element in the array, you would write “numbers[2]”. This is because indexing starts at 0, so the third element has an index of 2.

You can also manipulate array elements using indexes. Say, you’d like to change the value of an element by assigning a new value to it using the square bracket notation. Using our previous example:

numbers[2] = 10;
System.out.println(numbers[2]); // Output: 10

We first assign the value 10 to the third element in the array using the square bracket notation. Then, we print out the value of the third element to confirm that it has been changed to 10.

Another common array manipulation technique is sorting. You can sort arrays in Java using the “Arrays.sort()” method. Here’s an example:

int[] numbers = {5, 1, 3, 2, 4};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 4, 5]

Here, we have an array of integers named “numbers” with unsorted values. We use the “Arrays.sort()” method to sort the elements in ascending order. Then, we print out the sorted array using the “Arrays.toString()” method.

Multi-Dimensional Arrays 

So far, we have discussed one-dimensional arrays, which are arrays that have only one row of elements. However, Java also supports multi-dimensional arrays, which are arrays with multiple rows and columns of elements. Multi-dimensional arrays are useful for storing and manipulating data in a tabular format.

To declare a multi-dimensional array in Java, you must specify the number of rows and columns it will have, as well as the data type of the elements it will hold. For instance, to declare a two-dimensional array of integers with two rows and three columns, you would use the following syntax:

int[][] matrix = new int[2][3];

This initializes a two-dimensional array called a “matrix” with two rows and three columns, each holding integer values. You can also initialize a multi-dimensional array with values using nested curly braces. Consider the following:

int[][] matrix = {{1, 2, 3}, {4, 5, 6}};

This initializes a two-dimensional array called a “matrix” with two rows and three columns, each holding integer values. The first row contains the values 1, 2, and 3, while the second row contains the values 4, 5, and 6.

To access an element in a multi-dimensional array, you must use its row and column indices. For instance, to access the element in the first row and second column of the “matrix” array, you would write “matrix[0][1].” This is because the row index is 0 (the first row) and the column index is 1 (the second column).

Arrays vs ArrayLists in Java

Arrays and ArrayLists share some similarities, but they also have some significant differences that can impact when and how you use them. Let’s dive into the comparison between the two.

Simply put, an ArrayList is a resizable array that can change its size dynamically during runtime. This is unlike traditional arrays, which have a fixed length that cannot be altered once they are created.

Now, let’s take a look at how we can initialize an ArrayList:

ArrayList<Integer> numbers = new ArrayList<>();

This initializes an empty ArrayList. We can add elements to the ArrayList using the add() method:

numbers.add(1);
numbers.add(2);
numbers.add(3);

We can also remove elements from the ArrayList using the remove() method:

numbers.remove(2);

In this example, we are removing the element at index 2, which is the number 3. After this operation, the ArrayList will contain elements 1 and 2.

One of the most significant benefits of using ArrayLists is their flexibility. Because they can grow and shrink in size as needed, they can be a more efficient choice when dealing with large amounts of data. In contrast, arrays can be more limiting, as you must declare the size of the array upfront.

Another key difference between arrays and ArrayLists is how they are implemented in Java. Arrays are a fundamental data type, meaning they are built into the language itself. ArrayLists, on the other hand, are part of the Java collections framework, which provides a wide range of powerful data structures and algorithms for managing collections of objects.

Arrays vs Arraylists: Pros and Cons

Because of these differences, each data structure has its own set of benefits and drawbacks. Below are some of the main considerations when deciding whether to use an array or an ArrayList.

Benefits of Using Arrays

  • Fast and efficient for small amounts of data
  • Memory efficient, as they do not require the overhead of an ArrayList object
  • Compile-time safety, as the type and size of the array can be specified upfront

Cons of Using Arrays

  • Fixed-size, meaning you may need to allocate more memory than necessary, or reallocate memory if the size of the array changes
  • Can be challenging to work with when dealing with larger amounts of data
  • Cannot be resized, which means you need to create a new array and copy over the elements if you need to change the size 

Benefits of Using Arraylists

  • Dynamic size, which allows them to grow or shrink as needed 
  • Efficient for managing large amounts of data 
  • Can be easily sorted or searched using built-in methods

Drawbacks of Using Arraylists

  • Require more memory than traditional arrays, as they need to store additional information for resizing
  • Runtime safety, as the type of objects stored in an ArrayList can only be checked at runtime 
  • Less efficient than arrays for small amounts of data

So, if you’re dealing with a small amount of data and performance is critical, arrays may be the better choice. However, if you need to manage a large amount of data or require dynamic resizing, then an ArrayList may be the better option.

“Associative Arrays” in Java — Maps

Java does not support associative arrays but implements something similar through the Map data structure. A map, like an associative array, is a collection of key-value pairs, where each key maps to a corresponding value.

Maps are useful when you need to look up values based on a specific key, and can be implemented using several different classes in Java. Let’s take a look at how we can initialize a map using the HashMap class:

HashMap<String, Integer> phoneBook = new HashMap<>();

This initializes an empty HashMap with keys of type String and values of type Integer. We can add elements to the map using the put() method:

phoneBook.put(“John”, 1234567890);
phoneBook.put(“Jane”, 2345678901);

Here, “John” and “Jane” are the keys, and 1234567890 and 2345678901 are the corresponding values. We can also access a value in the map using its key:

int johnsPhoneNumber = phoneBook.get(“John”);

Here, johnsPhoneNumber will be assigned the value 1234567890.

Advantages of Using Maps

One advantage of using a map over an array or ArrayList is that the keys do not have to be integers. This means that you can use any object as a key, as long as it properly implements the equals() and hashCode() methods. This allows you to create custom key-value pairs for more complex data structures.

Maps also allow for fast lookups based on keys. Since the keys are unique in the map, you can quickly retrieve a value associated with a specific key without having to iterate through the entire data structure. This particularly helps when working with large datasets where quick access to specific values is important.

Another advantage of maps is that they can be used to simplify code in certain scenarios. For example, let’s say we have an algorithm that counts the frequency of words in a text file:

Map wordCounts = new HashMap<>();
// read in text file
for (String word : textFile) {
    if (wordCounts.containsKey(word)) {
        int count = wordCounts.get(word);
        wordCounts.put(word, count + 1);
    } else {
        wordCounts.put(word, 1);
    }
}

Here, we’re using an associative array to keep track of the frequency of each word in the text file. If the word is already in the associative array, we retrieve its current count using the get() method, increment the count, and then put the updated count back into the associative array. If the word is not yet in the associative array, we add it with a count of 1.

Briefly, maps simplify code and allow for efficient lookup of values based on their corresponding keys. If you find yourself frequently needing to look up values based on keys while working with large datasets, a map would allow you to do away with a lot of legwork.

The Bottom line

Arrays are an important data structure in Java and mastering them would go a long way in realizing their true power in Java. They are versatile, allowing you to create one-dimensional and multi-dimensional arrays that can hold primitive data types or objects.

With arrays, you can access elements using indexes and easily manipulate them through operations such as sorting. So, if you’re learning Java and looking to take your programming chops to the next level, arrays are a sure way to get you there.

Frequently Asked Questions

How do you find the length of an array in Java?

To find the length of an array in Java, you can use the length property. For example, if you have an array called “myArray”, you can find its length using the following syntax: “int length = myArray.length;”. This will give you the number of elements in the array.

Can you have an array with both primitive data types and objects in Java?

Yes, you can have an array with both primitive data types and objects in Java. This is called a mixed array.

For instance, you can create an array that contains both integers and strings by declaring it as “Object[] mixedArray = {1, 2, “hello”};”.

However, it is generally not recommended to use mixed arrays as they can be difficult to work with and can lead to type errors.

How can you convert an array to a list in Java?

To convert an array to a list in Java, you can use the Arrays.asList() method. If, say, you have an array called “myArray”, you can convert it to a list using the following syntax: “List<Object> myList = Arrays.asList(myArray);”. This will create a new list containing the elements of the original array.

What is the difference between an array and an ArrayList in Java?

The main difference between an array and an ArrayList in Java is that an array has a fixed length that cannot be changed once it is initialized, while an ArrayList is resizable and can change its size dynamically during runtime. Additionally, an array can only contain elements of a single data type, while an ArrayList can contain elements of any data type.

Can you change the size of an array once it has been initialized?

No, you cannot change the size of an array once it has been initialized. Arrays have a fixed length that is determined when they are created.

If you need to add or remove elements from an array, you will need to create a new array with the desired size and copy the elements from the old array to the new array. A

lternatively, you can use an ArrayList which is resizable and can change its size dynamically during runtime.

To top