Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
arrayutils
communitycreator

What is ArrayUtils.toStringArray() in Java?

abhilash

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;

Syntax

public static String[] toStringArray(Object[] array, String valueForNullElements)

Parameters

  • Object[] array: array of elements
  • String valueForNullElements: value to insert if the element in the array is null

The functions throws NullPointerException if array contains null.

Return value

A new string array that has the string representation of each element of the given array is returned.

Code

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;
        }

        @Override
        public 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);

    }
}

Expected output

Student Array is - [ Student{name='john', id=21}, Student{name='kelly', id=23}, Student{name='mac', id=25} ]

RELATED TAGS

java
arrayutils
communitycreator
RELATED COURSES

View all Courses

Keep Exploring