How To Convert Char Array To String In Java?

This tutorial is simple example for converting a character array into a simple string object. In general, there are two ways to convert the character array to string object, First approach is to pass the array into the string constructor and second approach is to using the String.valueOf(). Lets look at the example.

package javabeat.net.core;

public class CharArrayToStringExample {
	public static void main(String[] args) {

		char[] charArray = new char[] { 'a', 'b', 'c', 'd', '1', '2' };

		//Convert using String constructor
		String str1 = new String(charArray);
		System.out.println("String Constructor : " + str1);

		//Convert using String.valueOf method
		String str2;
		str2 = String.valueOf(charArray);
		System.out.println("String.valueOf() method : " + str2);
	}

}

Output…

String Constructor : abcd12
String.valueOf() method : abcd12

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*