You need to print the contents of an array variable. The long way to it is to user a loop to print each element of the array. To simplify this, you can use the Apache Commons Lang ArrayUtils.toString()
method. This method can take any array as a parameter and print out the contents separated by commas and surrounded by curly brackets. When you need to print a specific string when the array is null
, you can provide the second string
argument to this method.
package org.kodejava.commons.lang;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayUtilsToString {
public static void main(String[] args) {
// Print an int array as string.
int[] numbers = {1, 2, 3, 5, 8, 13, 21, 34};
System.out.println("Numbers = " + ArrayUtils.toString(numbers));
// Print string array as string.
String[] grades = {"A", "B", "C", "D", "E", "F"};
System.out.println("Grades = " + ArrayUtils.toString(grades));
// Print a multidimensional array as string.
int[][] matrix = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
System.out.println("Matrix = " + ArrayUtils.toString(matrix));
// Return "Empty" when the array is null.
String[] colors = null;
System.out.println("Colors = " + ArrayUtils.toString(colors, "None"));
}
}
The output of the code snippet above:
Numbers = {1,2,3,5,8,13,21,34}
Grades = {A,B,C,D,E,F}
Matrix = {{0,1,2},{1,2,3},{2,3,4}}
Colors = None
If you are using the JDK 1.5, or later, you can actually use the java.util.Arrays
class to do the same thing as the org.apache.commons.lang.ArrayUtils
class does.
Maven Dependencies
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024