How to convert Char Array to String in Java

  • 07 December 2016
  • ADM

 

How to convert Char Array to String in Java - images/logos/java.jpg

 

To convert char[] array to String in java there are two simple methods:

  • using String constructor
  • using static method String.valueOf.

Example

package com.admfactory;

public class CharArrayToString {

    public static void main(String[] args) {
	char[] sample = new char[] { 'S', 'a', 'm', 'p', 'l', 'e', ' ', 't', 'e', 'x', 't', '.' };

	String str0 = new String(sample);

	String str1 = String.valueOf(sample);

	System.out.println("char[] array to String example.");
	System.out.println();
	System.out.println("array: " + sample);
	System.out.println("new String: " + str0);
	System.out.println("String.valueOf: " + str1);
    }
}

Output

char[] array to String example.

array: [C@7004ba66
new String: Sample text.
String.valueOf: Sample text.

 

References