Char Array to String Java

Sometimes, it may be required in coding to convert array to string. The array may be in the form of characters or byte.

Two styles exist to convert array to string. One is using String constructor and the other using copyValueOf()() method.

Following example converts char array to string.
import java.util.Arrays;
public class ArrayToString
{
  public static void main(String args[])
  {
    char alphabets[] = { 'Z', 'Y', 'X', 'W', 'V', 'U' };
    System.out.println("\nchar array to be converted: " + Arrays.toString(alphabets));
    String alphabetsString = new String(alphabets);
    System.out.println("First style char array in string form: " + alphabetsString);

    String str1 = String.copyValueOf(alphabets);            
    System.out.println("Second style char array in string form: " + str1);
  }
}

Char Array to String JavaOutput Screenshot on Char Array to String Java

In the above example all the characters are of the char array are converted into string. To convert a few characters of char array and also to convert byte array elements see Array to String.

Leave a Comment

Your email address will not be published.