Java remains one of the world's most popular programming languages due to its platform independence. Many new developers learn Java as their first language. Java is known for being verbose, and some developers struggle to get the basics down.
Understanding data structures is a key component of Java programming, and arrays are the first step. To help your Java journey, in this tutorial, we will learn how to implement and use arrays in Java. A Java array is a group of similarly-typed variables that use a shared name.
Today, we will learn what's unique about arrays in Java syntax and explore how to declare, initialize, and operate on array elements.
Today, we will learn:
- What are arrays in Java?
- Types of arrays in Java
- Declaring an array in Java
- Initializing an array in Java
- Accessing and changing elements of an array
- Looping through array elements
- Common Java array operations
- What to learn next
What are arrays in Java?
A variable is a location in our program with a name and value. This value could be any data type, like int. An array is another variable type or a container object with a fixed number of values that are all of a single type. In other words, a collection of similar data types. When an array is created, the size of the array (or length) is also fixed.
Simplified: Think of a Java array as a box with many compartments, and inside each compartment is one value.
The compartments in the box must remain ordered using indexing. Array elements are indexed, and each index should point to an element. It will look something like this:
INDICES => index 0->index 1->index 2->index 3->...index n
ELEMENTS => element 1->element 2->element 3->element 4->....element n+1
Each compartment has a numerical index that we use to access a value. An array index always begins with 0. So, say we have 10 compartments in an array container box. There will be 10 indices, but they start from 0 and end at 9 because the index 0 points to the first element 1.
What's unique about arrays in Java?
Arrays in every language will differ slightly. Here are the unique qualities of arrays in Java that differ from other languages you may use, like C or C++.
- Arrays are dynamically allocated
- Arrays are objects in Java
- A Java array variable is declared like other variables
- The variables are ordered, with the index beginning at 0
- The superclass of the array type is
Object
- The size of an array is specified with an
int
value
Types of arrays in Java
In Java, there are a few different types of arrays that we can work with.
A one-dimensional array is a normal array that you will use most often. This type of array contains sequential elements that are of the same type, such as a list of integers.
int[] myArray = {10, 20, 30, 40}
A multidimensional array is an array of arrays. A two-dimensional array is an array made up of multiple one-dimensional arrays. A three-dimensional array is an array made up of multiple two-dimensional arrays.
// Two-dimensional array
int[][] a = new int[3][4];
// Three-dimensional array
String[][][] data = new String[3][4][2];
An array of objects is created just like an array of primitive data types.
Student[] arr = new Student[4];
//This is a user-defined class
The ArrayList is a class that is a resizable array. While built-in arrays have a fixed size, ArrayList
can change their size dynamically, so the elements of the array can be added and removed using methods, much like vectors in C++.
Note:
ArrayList
is included in thejava.util
package.
import java.util.ArrayList; //import the ArrayList class
class MyClass {
public static void main( String args[] ) {
ArrayList<String> shapes = new ArrayList<String>(); // Create an ArrayList object with a string data type
}
}
Declaring an array in Java
Now that we know the types of arrays we can use, let's learn how to declare a new array in Java. Here is the basic syntax for array declaration.
dataType[] arrayName;
-
dataType
: this can be any Java object or primitive data type (such as int, byte, char, boolean, etc.) -
arrayName
: this is an identifier so you can access the array
Let's create a simple array in Java to understand the syntax. First, declare the variable type using square brackets []
.
String[] dogs;
Now we have a variable that holds an array of strings. We can insert values using an array literal. We place our values in a list separated by commas that are held within curly brackets {}
.
String[] dogs = {"Pitbull", "Poodle", "Lab", "Pug"};
Creating an array of integers will look like this:
int[] myNum = {5, 10, 15, 20};
As we learned, arrays have a fixed amount of elements. We have to define the number of elements that our array will hold to allocate memory. Here's the basic syntax for memory allocation.
// declaring an array
double[] data;
// allocating memory
data = new Double[5];
Above, the array can store 5 elements, meaning the length of the array is 5. For another example, say we want to store the names of 50 people. We create an array of the string type. The array below can only store up to 50 elements.
String[] array = new String[50];
There are other ways to declare an array in Java. Here are the three options:
int[] myNumberCollection = new int[5];
int[] myNumberCollection; myNumberCollection = new int[5];
int[] myNumberCollection = {1, 2, 56, 57, 23};
In the first two cases, we add elements to the array container manually. In the third case, we added the elements when we declared the array.
// initializing the first element
myNumberCollection[0] = 1;
// initializing the second element
myNumberCollection[1] = 2;
Note: The official Java documentation recommends using the following format to declare an array:
public static void main(String[] args){}
.
Initializing an array in Java
In Java, we can declare and initialize arrays at the same time.
- Initialization occurs when data is assigned to a variable.
- Declaration occurs when the variable is created.
So, when you first create a variable, you are declaring it but not necessarily initializing it yet.
Here's an example of how to declare and initialize values in Java:
//declare and initialize an array
int[] age = {25, 50, 23, 21};
Above, we declared an array using int[] age
and initialized it by assigning the values {25, 50, 23, 21}
.
Note: You don't need to declare the size of the array because the Java compiler automatically counts the size for you.
We can also initialize arrays using the index number, as shown below:
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 25;
age[1] = 50;
...
Accessing and changing elements of an array
We access the elements of an array by referencing its index number. Remember, the index begins with 0 and ends at the total array length, minus one. You can access all elements of an array using a for
loop. Loops are used in programming to perform repetitive tasks that require conditions.
Syntax for accessing elements of an array:
// access array elements
array[index]
Let's continue using our dogs
example from before. Below, we want to write a program that can find the first value of the array and then print the result.
class Main {
public static void main(String[] args) {
// create an array
String[] dogs = {"Pitbull", "Poodle", "Lab", "Pug"};
// access first element
System.out.println("First Element: " + dogs[0]);
}
}
-->
First Element: Pitbull
Note: In Java, you can use
System.out.println()
to print a value.
We can also change the value of an element through its index number. Using our example above, say we want to change Pitbull
to Terrier
.
class Main {
public static void main(String[] args) {
String[] dogs = {"Pitbull", "Poodle", "Lab", "Pug"};
System.out.println("Before update" + dogs[0]); // print old value
dogs[0] = "Terrier"; // changing value
System.out.println("After update" + dogs[0]); // print new value
}
}
-->
Before updatePitbull
After updateTerrier
Looping through array elements
We can also loop through each element of the array. In Java, there are multiple methods for looping over an array. You can use for
, the enhanced for
loop (aka for-each), while
, or do-while
loop.
A traditional
for
loop allows you to iterate until you reach the last element. Enhancedfor
loops allow you to iterate without dealing with counts.
Instead of printing each element, you can use a for
loop to iterate through the array. The array will start iterating at the index 0
and traverse the length of the array.
Let's look at an example of a for
loop to see how it works in Java. Below, we use the Java for
loop to iterate through each array element. We use the .length
property to get the size of our array.
class Main {
public static void main(String[] args) {
// create an array
int[] age = {3, 2, 7, 8};
// loop through the array with the for loop
System.out.println("Using the for loop: ");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
}
-->
Using the for loop: 3 2 7 8
Note:
for
loops in Java are identical to those found written in C and JavaScript.
Common Java array operations
Once we create and initialize our arrays, we need to learn how to manipulate and use them. There is a lot we can do with arrays in Java. These kinds of operations are very common questions in coding interviews. Here are examples of some of the operations you can do on Java arrays.
Get the first and last element
This is one of the most common tasks we can do with Java arrays due to its index-based organization. First, we declare and initialize an array of integers using int
.
Then we use the index value 0
and the .length
attribute to retrieve specific elements.
class Main {
public static void main(String[] args) {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
int firstItem = array[0];
int lastItem = array[array.length - 1];
}
}
Add a new item to an Array
Since Java can only allocate elements to an array up to a certain size (2,147,483,647 elements), we cannot add items that exceed this limit. Instead, we can declare a larger array and copy the elements of the smaller array into it.
The Arrays
class contains various methods for manipulating arrays, including the ability to replicate the values of an array.
int[] newArray = Arrays.copyOf(array, array.length + 1);
newArray[newArray.length - 1] = newItem;
Convert a list to an array
There are two variants of this method:
-
toArray()
: This method returns an array of typeObject[]
whose elements are all in the same sequence as they are in the list. Casting is used to specify each element’s type when performing some operations.
import java.util.ArrayList;
public class ListToArray {
public static void main(String[] args) {
// A list of size 4 which is to be converted:
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
// ArrayList converted to Object[] array:
Object[] objArr = list.toArray();
for(Object obj: objArr){
// Using casting before performing addition:
System.out.println((Integer)obj + 1);
}
}
}
}
-
toArray(T[] arr)
: This variant takes an already defined array as its parameter. When the array’s size is greater than or equal to the size of the list, then the array is filled with the elements of the list. Since the type of the returned array is specified by the parameter’s type, casting is unnecessary.
import java.util.ArrayList;
public class ListToArray {
public static void main(String[] args) {
// A list of size 4 to be converted:
ArrayList<Integer> list = new ArrayList<>();
list.add(2);
list.add(3);
list.add(4);
list.add(5);
// Declaring an array of size 4:
Integer[] arr = new Integer[4];
// Passing the declared array as the parameter:
list.toArray(arr);
// Printing all elements of the array:
System.out.println("Printing 'arr': ");
for(Integer i: arr)
System.out.println(i);
// Declaring another array of insufficient size:
Integer[] arr2 = new Integer[3];
// Passing the array as the parameter:
Integer[] arr3 = list.toArray(arr2);
// Printing the passed array:
System.out.println("\n'arr2' isn't filled because it is small in size: ");
for(Integer i: arr2)
System.out.println(i);
// Printing the newly allocated array:
System.out.println("\n'arr3' references the newly allocated array: ");
for(Integer i: arr3)
System.out.println(i);
}
}
Get a random value
We can use the object, java.util.Random
, to access any value of the array at random.
int anyValue = array[new Random().nextInt(array.length)];
Insert a value between two other values
Inserting an item in an array between two others is somewhat tricky. The class ArrayUtils
was created to make this possible. Here, we specify the index where we want to insert the value. Our output should be a new array containing an updated number of elements.
int[] largerArray = ArrayUtils.insert(2, array, 77);
Check if an array is empty
We can use the .length
attribute to check if an array is empty or not using a boolean.
boolean isEmpty = array == null || array.length == 0;
The ArrayUtils
helper class also offers a null-safe method for this process, but this function depends on the length of the data structure.
boolean isEmpty = ArrayUtils.isEmpty(array);
What to learn next
Congrats! You should now have a good idea of how arrays work in Java. There is still more to learn! There are so many array operations that we can perform, and many of these are asked during coding interviews.
Take a look at this list to get an idea of what to learn next:
- Copy an array in Java
- Box and unbox an array
- Shuffle elements of an array
- Find the
min
andmax
in an array with Java - Remove the first element of an array
- Find the sum and average of a Java array
- Invert an array in Java
Or, you can find out how to learn Java from scratch!
The best way to learn Java is through hands-on practice. Check out Educative's definitive Java course A Complete Guide to Java Programming to continue learning these operations and beyond. There are lots of interactive Java tutorials and lessons to help you nail the fundamentals of programming and more advanced topics like iterative constructs, useful algorithms, and data structures.
This course will get you on the fast track to becoming a proficient and modern Java developer. You can even earn a certificate to add to your resume!
Happy learning!
Continue reading about Java on Educative
- 5 simple and effective Java techniques for strings and arrays
- Crack the Top 40 Java Coding Interview Questions
- How to use Stack and Queues in Java
Start a discussion
What is your favorite Java structure or algorithm? Was this article helpful? Let us know in the comments below!
Top comments (0)