Array to String Java


After knowing how to convert string to array, let us find the other way of converting array to string.
The job is done simply by String overloaded constructors and overloaded copyValueOf() method. Following are signatures as defined in String class.
  1. public String(char[] charArray): A new string is created with the characters of charArray.
  2. public String(byte[] byteArray): A new string is created with the bytes of byteArray. The bytes are decoded to characters and then copied to new string.
  3. public String(char[] charArray, int offset, int count): Not all characters of the array copied. Copied count number of characters from the offset. offset is the index number from where copied.
  4. public String(byte[] byteArray, int offset, int count): Not all bytes of the array copied. Copied count number of bytes from the offset. offset is the index number from where copied.
  5. public static String copyValueOf(char[] charArray): Creates and returns a new string with all the elements of charArray.
  6. public static String copyValueOf(char[] charArray, int offset, int count): Creates and returns a new string with count number of characters of charArray staring from index number offset.
See the example on array to string where all the elements of both character array and byte array are converted to strings.
import java.util.Arrays;
public class ArrayToString
{
  public static void main(String args[])
  {
    char lettersArray[] = { 'A', 'B', 'C', 'D', 'E', 'F' };
    System.out.println("char array: " + Arrays.toString(lettersArray));
    String lettersString = new String(lettersArray);
    System.out.println("First style char array in string form: " + lettersString);

    String str1 = String.copyValueOf(lettersArray);             // another way
    System.out.println("Second style char array in string form: " + str1);

    byte byteArray[] = { 65, 66, 67, 68, 69, 70 };
    System.out.println("\nbyte array: " + Arrays.toString(byteArray));
    String byteString = new String(byteArray);
    System.out.println("byte array in string form: " + byteString);
  }
}

Output Screen on Array to String Java

The above example converts whole arrays to strings. The next example converts a few elements of the array to string,
import java.util.Arrays;
public class ArrayToString
{
public static void main(String args[])
{
char lettersArray[] = { 'A', 'B', 'C', 'D', 'E', 'F' };
System.out.println("\nchar array: " + Arrays.toString(lettersArray));
String lettersString = new String(lettersArray, 1, 4);
System.out.println("First st