SoFunction
Updated on 2025-03-10

Several ways to convert arrays into strings in Java

Methods to convert arrays into strings:

1. Use Arrays tool class ()

int[] array = {1, 2, 3, 4, 5};
String s = (array);
       (s);// [1, 2, 3, 4, 5] What you get is not the desired result, you can use string intercept to get the desired result
        s = (1, ("]"));
        (s);// 1, 2, 3, 4, 5

2. Use StringBuilder to create an object, and use append() to append elements in the array to the object.

StringBuilder sb = new StringBuilder();
        // 2-1. Iterate through the array        for (int i = 0; i < ; i++) {
            // 2-2. Append elements to the object            (array[i]);
            // 2-3. Add the middle connector to get 1--2--3--4-5            if (i !=  - 1) {
                ("--");
            }
        }
        (sb);// 1--2--3--4--5

3. Use Stream Streaming

Two ways to transform into streams:

​ 1. () When using this method, if the array is a basic type, boxed() is required to be encapsulated. If the array is an encapsulated type, boxed() is not required to be encapsulated.

​ 2. () The array needs to be encapsulated type using this method. For example: Integer

s = (array)// Convert array to stream           .boxed()// Encapsulate the int type into Integer            .map(item -> (item))// Convert Integer to string             .collect((","));// Splice, separate with ',' (s);// Get results 1,2,3,4,5
 Integer[] array1 = {1, 2, 3, 4, 5};
String s1 = (array1)
                .map(item -> (item))
                .collect(("-"));
  (s1);// Get results 1-2-3-4-5

Attachment: String to character array

First look at the string type converted to a char array, the code is as follows
The code is as follows:

String myString = "hello123"; //Create a string variable myString	char[] myCharArray; //Create a character array myCharArray	myCharArray = (); //Convert string variables to character array	for(int i=0; i<; i++) {
	    (myCharArray[i] + " "); //Print each character out	}

result:

h e l l o 1 2 3

Obviously, the string method toCharArray() is used during the conversion process, converting the string "hello123" into a character array.

Summarize

This is the end of this article about how to convert arrays into strings in Java. For more related content on Java array conversion, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!