toStringArray
is a static method of the ArrayUtils
class that returns a new string array that contains the string representation of each element of the given array. The toString
method is called on each element to obtain the string representation of each element.
ArrayUtils
is defined in the Apache Commons Lang
package. Apache Commons Lang
can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the ArrayUtils
class as follows.
import org.apache.commons.lang3.ArrayUtils;
public static String[] toStringArray(Object[] array, String valueForNullElements)
Object[] array
: array of elementsString valueForNullElements
: value to insert if the element in the array is nullThe functions throws
NullPointerException
if array contains null.
A new string array that has the string representation of each element of the given array is returned.
In the code below, we define a custom Student
class and create an array of student instances. Next, we use the toStringArray
method to get the string array of the student object array.
import org.apache.commons.lang3.ArrayUtils;public class Main {static class Student{public String name;public int id;public Student(String name, int id) {this.name = name;this.id = id;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", id=" + id +'}';}}private static void printArray(String[] array){System.out.print("[ ");for(String i:array) System.out.print( i + ", ");System.out.println("]");}public static void main(String[] args) {Student[] students = {new Student("john", 21),new Student("kelly", 23),new Student("mac", 25)};String[] studentStrings = ArrayUtils.toStringArray(students);System.out.print("Student Array is - ");printArray(studentStrings);}}
Student Array is - [ Student{name='john', id=21}, Student{name='kelly', id=23}, Student{name='mac', id=25} ]