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 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 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 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.12.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023