Table of Contents
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.
Creation
Creating an array in Java is pretty straightforward. Let's create one that contains strings:
JAVAString[] 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:
JAVAString[] colors = new String[3];
In both cases, an array of size 3
is created.
Retrieval
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:
JAVAString[] colors = { "red", "green", "blue" };
System.out.println(colors[1]);
BASHgreen
You can take this further and print the entire array, like this:
JAVAString[] colors = { "red", "green", "blue" };
for (int i = 0; i < colors.length; i++) {
System.out.println(colors[i]);
}
BASHred
green
blue
We simply iterate through all the values between 0
and the length of the array to get every element in that 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:
JAVAString[] colors = { "red", "green", "blue" };
colors[1] = "yellow"; // reassignment
for (int i = 0; i < colors.length; i++) {
System.out.println(colors[i]);
}
BASHred
yellow
blue
Sort
You can easily sort a Java array by calling the sort()
method:
JAVAString[] colors = { "red", "green", "blue" };
Arrays.sort(colors);
for (int i = 0; i < colors.length; i++) {
System.out.println(colors[i]);
}
BASHblue
green
red
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Getting Started with Express
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Getting Started with Moment.js
- Setting Up Stylus CSS Preprocessor