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:

JAVA
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:

JAVA
String[] 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:

JAVA
String[] colors = { "red", "green", "blue" }; System.out.println(colors[1]);
BASH
green

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

JAVA
String[] colors = { "red", "green", "blue" }; for (int i = 0; i < colors.length; i++) { System.out.println(colors[i]); }
BASH
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.

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:

JAVA
String[] colors = { "red", "green", "blue" }; colors[1] = "yellow"; // reassignment for (int i = 0; i < colors.length; i++) { System.out.println(colors[i]); }
BASH
red yellow blue

Sort

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

JAVA
String[] colors = { "red", "green", "blue" }; Arrays.sort(colors); for (int i = 0; i < colors.length; i++) { System.out.println(colors[i]); }
BASH
blue green red
Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.