Convert character array to String in Java

static String copyValueOf(char[] a), static String copyValueOf(char[] a,int offset,int count) , static String valueOf(char[] data) and static String valueOf(char[] data,int offset,int count) methods of String class can be used to convert a character array to String object in Java.

Since the methods are static, we can access the method directly with its class name String. i.e String.copyValueOf(char[] a)


Example 1 ( copyValueOf(char[] a) )

class StringTest{

public static void main(String args[]){

char a[]={'a','b'};

String str=String.copyValueOf(a);

System.out.println("Value of string variable is "+ str);

}

}

Output 1

Value of string variable is ab


Example 2 ( copyValueOf(char[] a,int offset,int count) )

class StringTest{

public static void main(String args[]){

char a[]={'a','b','1','2'};

String str=String.copyValueOf(a,1,3);

System.out.println("Value of string variable is "+ str);

}

}

Output 2

Value of string variable is b12


Example 3 ( valueOf(char[] a) )

class CaToStrTest{

public static void main(String args[]){

char cA[]={'z','y','x','w'};

String str=String.valueOf(cA);

System.out.println("Value of string variable is "+ str);

}

}

Output 3

Value of string variable is zyxw


Example 4 ( valueOf(char[] a,int offset,int count) )

class CaToStrTest{

public static void main(String args[]){

char sA[]={'1','2','3','4'};

String str=String.valueOf(sA,1,2);

System.out.println("Value of string variable is "+ str);

}

}

Output 4

Value of string variable is 23