How to convert Array to String in Java

When working with Java, there may be times when we need to know how to convert an array to string in Java. This can be useful when printing out the contents of an array or when passing the array as a parameter to a method. Converting an array to a string in Java is a common task often required when working with text-based data. The process of converting an array to a string involves taking the elements of the array and concatenating them into a single string. This can be useful when passing data between methods or when writing data to a file or database. In Java, there are several methods available to convert an array to a string, each with its own advantages and disadvantages.

In this tutorial, we will discuss different approaches for converting an array to a string in Java.

Need for Converting Array To String In Java

The topic of converting an array to a string in Java is relevant in various scenarios, including

  • Displaying data in a User-friendly format: When we want to display the contents of an array in a user-friendly format, such as printing the array to the console or a log file.
  • Passing as argument: When we want to convert an array to a string to pass it as an argument to a method or function.
  • Writing operation: When we want to write the contents of an array to a file or database.

How to change array to string in java

There are several approaches to convert an array to a string in Java. Some of them are:

  • Using Arrays.toString() method
  • Using StringBuilder
  • Using Java 8 Streams
  • Using Apache Commons Lang library

While choosing the best approach, factors like performance, code readability, and the size of the array should be kept in mind.

Approach 1: Using Arrays.toString() method

This method is the simplest and quickest approach to convert an array to a string in Java. The method is a part of the Arrays class, which provides a static method that takes an array and returns its string representation.

Example:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Input
        int[] arr = {1, 2, 3, 4, 5};
        
        // Using Arrays.toString() method to convert array to string
        String arrStr = Arrays.toString(arr);
        
        // Output
        System.out.println(arrStr); // [1, 2, 3, 4, 5]
    }
}

Output:

 [1, 2, 3, 4, 5]

Explanation:

  • First, we create an array of integers.
  • Then, we use the Arrays.toString() method to convert the array to a string.
  • Finally, we print the string representation of the array.

Approach 2: Using StringBuilder

This approach involves creating a StringBuilder object and appending the elements of the array to it, separated by a delimiter. The resulting string can be obtained by calling the toString() method of the StringBuilder object.

Example:

public class Main {
    public static void main(String[] args) {
        // Input
String[] arr = {"John", "Doe", "Jane", "Doe"};
// Using StringBuilder to convert array to string
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < arr.length; i++) {
    sb.append(arr[i]);
    if (i < arr.length - 1) {
        sb.append(", ");
    }
}
sb.append("]");
String arrStr = sb.toString();
// Output
System.out.println(arrStr);
    }
}

Output:

 [ John, Doe, Jane, Doe ]

Explanation:

  • First, we create an array of strings.
  • Then, we create a StringBuilder object and append each element of the array to it.
  • We also add commas and brackets to format the string representation of the array.
  • Finally, we convert the StringBuilder object to a string using the toString() method.

Approach 3: Using Java 8 Streams

In this approach, we use the Java 8 Streams API to convert an array to a string. Here’s how it works:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // Input
        String[] arr = {"blue", "yellow", "orange", "red"};
        
        // Using Java 8 Streams to convert array to string
        String arrStr = Arrays.stream(arr).collect(Collectors.joining(","));
        
        // Output
        System.out.println(arrStr); 
    }
}

Output:

blue,yellow,orange,red

Explanation:

  • First, we create an array of strings.
  • Then, we use the Arrays.stream() method to create a stream of the array.
  • We then use the Collectors.joining() method to join the elements of the stream with a comma separator.
  • Finally, we convert the stream to a string using the collect() method.

Approach 4: Using Apache Commons Lang library

In this approach, we use the join() method from the Apache Commons Lang library to convert an array to a string. Here’s how it works:

Here’s how it works:

import org.apache.commons.lang3.StringUtils;

public class Example {
  public static void main(String[] args) {
    String[] arr = { "apple", "banana", "cherry", "date" };
    String str = StringUtils.join(arr, " | ");
    System.out.println(str);
  }
}

Output:

apple | banana | cherry | date

Explanation:

  • We first create a string array arr with some values.
  • We use the join method from the Apache Commons Lang library’s StringUtils class to join the strings in the array with a custom separator. In this case, we use the vertical bar (|) as the separator.
  • The resulting string is then printed to the console.

Note: To use the Apache Commons Lang library, you need to download the library from the Apache Commons website and include the relevant JAR file in your project’s classpath.

Best Approach to convert an array to a string in Java

Arrays.toString() is the best method when considering how to convert array to string in Java for the following reasons:

  • Simplicity: Arrays.toString() is the simplest approach among the four, requiring only a single method call to convert the array to a string.
  • Readability: The resulting string generated by Arrays.toString() is easy to read and understand, as it uses square brackets and commas to represent the array.
  • Standardization: Arrays.toString() is a built-in method in Java, which means that it is available to all Java developers and does not require any external libraries or dependencies.
  • Performance: Arrays.toString() is generally faster than the other three approaches, as it has minimal overhead and does not require any additional method calls or object creation.

Sample Problem 1:  Using Arrays.toString() method

Suppose you are a software developer and you are working on a project that involves sending an email notification to users. One of the requirements is to include a list of recent updates in the email body. You have the updates stored in an array of strings, and you need to convert this array to a string so that it can be included in the email body.

Write a Java program to convert an array of strings to a single string using the Arrays.toString() method.

Input Array: {“Update 1: Bug fix”, “Update 2: Feature enhancement”, “Update 3: Security patch”}

Solution:

We first import the java.util.Arrays package to use the Arrays class and its methods.

  • In the main method, we declare a string array arr and initialize it with some values.
  • We then use the Arrays.toString() method to convert the arr array to a string representation, and store it in the arrString variable.
  • Finally, we print the arrString variable to the console along with a message to verify that the array has been successfully converted to a string.
import java.util.Arrays;

public class ArrayToStringExample {
    public static void main(String[] args) {
        // Input array
        String[] arr = {"Update 1: Bug fix", "Update 2: Feature enhancement", "Update 3: Security patch"};

        // Converting array to string using Arrays.toString() method
        String arrString = Arrays.toString(arr);

        // Output string
        System.out.println("Array as string: " + arrString);
    }
}

Output:

Array as string:  [Update 1: Bug fix, Update 2: Feature enhancement, Update 3: Security patch]

Sample Problem 2: Using StringBuilder

A school wants to display the student ID numbers of a particular class as a string. The student IDs are stored in an integer array. The school wants the IDs to be displayed as a single string with spaces or separators between them.

Input:

The school has a class of 20 students, and their IDs are stored in an integer array named studentIDs. The IDs are in the range of 1001 to 1020.


Solution:

The program takes an integer array studentIDs as input, which contains the student ID numbers.

  • The StringBuilder class is used to concatenate the integers in the array into a string.
  • A loop is used to iterate over the array, and each integer is appended to the StringBuilder object using the append() method.
  • The toString() method is used to convert the StringBuilder object to a string.
  • The resulting string is stored in the variable studentIDStr.
  • Finally, the program prints the resulting string with the message “Student ID numbers as string: ” using the println() method.
  public class Main {
    public static void main(String[] args) {
        // Input
        int[] studentIDs = {1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020};
        // Using StringBuilder to convert array to string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < studentIDs.length; i++) {
            sb.append(studentIDs[i]+” “);
        }
        String studentIDStr = sb.toString();
        // Output
        System.out.println("Student ID numbers as string: " + studentIDStr); // 
    }
}

Output:

Student ID numbers as string: 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 

Sample Problem 3: Using Java 8 Streams

Suppose you have an e-commerce website that sells different types of fruits in the form of baskets. Each basket contains different types of fruits. You have an array containing the names of fruits in each basket. You want to display the list of fruits in each basket as a string with a comma-separated format to show to the customers.

Problem Statement: Given an array of fruits in each basket, convert the array to a string using Java 8 Streams and display it as a comma-separated string to show it to the customers.

Input:  String[] fruits = {“apple”, “banana”,”orange”,”grape”};

Solution:

  • First, we create an array of strings.
  • Then, we use the Arrays.stream() method to create a stream of the array.
  • We then use the Collectors.joining() method to join the elements of the stream with a comma separator.
  • Finally, we convert the stream to a string using the collect() method.
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // Input
        String[] arr = {"apple", "banana", "orange", "grape"};
        
        // Using Java 8 Streams to convert array to string
        String arrStr = Arrays.stream(arr).collect(Collectors.joining(","));
        
        // Output
        System.out.println(arrStr); // apple,banana,orange,grape
    }
}

Output:

apple,banana,orange,grape

Sample Problem 4: Using Apache Commons Lang library

You are working on a project where you need to read a barcode image that is scanned by a barcode reader. The image contains a series of characters that represent the barcode data. You need to convert the characters into a string for further processing.

To accomplish this, you have received an array of characters representing the barcode data. You need to convert this array to a string so that you can perform operations such as searching, filtering, and analyzing the data.

You have decided to use the Apache Commons Lang library to convert the array of characters to a string. The StringUtils.join() method of this library takes an array of characters and joins them to form a string.

Input:  char[] arr = {‘B’, ‘A’, ‘R’, ‘C’, ‘O’, ‘D’, ‘E’};


Solution:

  • First, we create an array of characters.
  • Then, we use the StringUtils.join() method from the Apache Commons Lang library to join the elements of the array with an empty string separator.
  • Finally, we assign the result to a string variable.
import org.apache.commons.lang3.StringUtils;

public class Main {
    public static void main(String[] args) {
        // Input
        char[] arr = {'B', 'A', 'R', 'C', 'O', 'D', 'E'};
        
        // Using Apache Commons Lang library to convert array to string
        String arrStr = StringUtils.join(arr, "");
        // Output
        System.out.println(arrStr); 
    }
}

Output:

BARCODE

Conclusion on how to change array to string in java


Converting an array to a string in Java is a common task that is often required when working with text-based data.

Converting an array to a string in Java can usually be done in 4 ways, but the best approach is to use the Arrays.toString() method. It is simple, fast, and provides a standard format for the output string.

Knowing how to efficiently go from an array to a string can be a useful skill to have when constructing programs. However, it’s always recommended to try all the approaches and choose the best approach based on the specific use case.