StackTips

Working with Java Arrays

stacktips avtar

Written by:

Editorial,  5 min read,  updated on December 21, 2023

One of the most common collections in Java are arrays. Arrays can be thought of as simply a list of data, and that data can take the form of numbers, strings, objects, even arrays themselves.

Defining an Array

Creating an array in Java is pretty straightforward. Let's create one that contains strings:

String[] colors = { "red", "green", "blue" };

That right there is an array of 3 string elements assigned to the variable colors.

Arrays in Java have a set size. You can either initialize it like previously shown, or like this:

String[] colors = new String[3];

In both cases, an array of size 3 is created.

Retrieve Array Element

Now that we can create arrays, let's learn how to get an element back when we want to use it. Arrays in Java start counting from 0. This means that the 3rd element in the array has an index of 2.

With this in mind, let's get the second element from our original array:

String[] colors = { "red", "green", "blue" };

System.out.println(colors[1]);
green

You can take this further and print the entire array, like this:

String[] colors = { "red", "green", "blue" };

for (int i = 0; i < colors.length; i++) {
    System.out.println(colors[i]);
}
red
green
blue

We simply iterate through all the values between 0 and the length of the array to get every element in that array.

Array Reassignment

Once you have initialized an array with values, you can modify each individual element pretty easily. Simply reassign the element's value like you would any variable:

String[] colors = { "red", "green", "blue" };
colors[1] = "yellow"; // reassignment

for (int i = 0; i < colors.length; i++) {
    System.out.println(colors[i]);
}
red
yellow
blue

Sorting Array

You can easily sort a Java array by calling the sort() method:

String[] colors = { "red", "green", "blue" };
Arrays.sort(colors);

for (int i = 0; i < colors.length; i++) {
    System.out.println(colors[i]);
}
blue
green
red

Getting Started with Spring Boot: A Beginner's Guide

This course covers the fundamentals of Spring Boot an you will gain the necessary skills to develop various types of applications using the powerful features of the Spring Boot framework.

>> CHECK OUT THE COURSE

Continue reading..