How to convert Char Array to String in java

There are multiple ways to convert Char Array to String in java.

Some of them are:
  • Using String class's constructor (By passing Char array to contructor)
  • Using String class's valueOf method
  • Using iterating char array

Example:

package org.arpit.java2blog;

public class CharArrToStringMain {
 /*
  * @ Author : Arpit Mandliya
  */
 public static void main(String args[]) {
  char[] charArr = { 'J', 'a', 'v', 'a', '2', 'b', 'l', 'o', 'g' };

  // Using String's constructor
  System.out.println("--------------------");
  System.out.println("Using String's contructor");
  System.out.println("--------------------");
  String str = new String(charArr);
  System.out.println(str);
  System.out.println();

  // Using String's valueOf method
  System.out.println("--------------------");
  System.out.println("Using String's valueOf");
  System.out.println("--------------------");
  String strV = String.valueOf(charArr);
  System.out.println(strV);
  System.out.println();

  // Using iterating char Array
  System.out.println("--------------------");
  System.out.println("Using iterating char Array");
  System.out.println("--------------------");
  String strT = "";
  for (int i = 0; i < charArr.length; i++) {
   strT += charArr[i];
  }
  System.out.println(strT);
 }
}

When you run above program, you will get below output
--------------------
Using String's contructor
--------------------
Java2blog

--------------------
Using String's valueOf
--------------------
Java2blog

--------------------
Using iterating char Array
--------------------
Java2blog

Other String Programs are :

    How to convert String to char Array in java How to reverse String in java Find length of String without using java inbuilt length method Find all substrings of String in java Find First non repeated character in a String Java Program to check Palindrome String


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012