How to convert Char Array to String and String to Char Array in Java?

Overview

In this tutorial, we show you how to create Java application examples to convert Char Array to String And String to Char Array using Eclipse IDE.



How to convert Char Array to String and String to Char Array in Java

Watch Tutorial

Project Structure

The following screenshot shows final structure of the project.
Project Structure convert Char Array to String And String to Char Array

Creating the Project

  • Launch Eclipse IDE.
  • Go to File-> New-> Others... Select Java Project under Java category then click Next.
  • Type "CharArrayAndStringExample" in the "Project Name" field
  • Click Finish.

Convert Char Array to String

To convert char[] array to String in java there are two simple methods.
  1. Using valueOf() method of String class.
  2. Using String Constructor.
Create a CharArrayToString class under com.jackrutorial package and write the following code in it.
CharArrayToString.java
package com.jackrutorial;

public class CharArrayToString {

 public static void main(String[] args) {
  char[] c = new char[] {'w','w','w','.','j','a','c','k','r','u','t','o','r','i','a','l','.','c','o','m'};
  
  //option 1
  String str1 = String.valueOf(c);
  System.out.println("option 1: " + str1);
  
  //option 2
  String str2 = new String(c);
  System.out.println("option 2: " + str2);
 }
}

Output


option 1: www.jackrutorial.com
option 2: www.jackrutorial.com

Convert String to Char Array

We using toCharArray() method. This method converts string to character array.
Create a StringToCharArray class under com.jackrutorial package and write the following code in it.
StringToCharArray.java
package com.jackrutorial;

public class StringToCharArray {

 public static void main(String[] args) {
  String str = "www.jackrutorial.com";
  
  char[] c = str.toCharArray();
  for(char ch : c) {
   System.out.println(ch);
  }
 }
}

Output

w
w
w
.
j
a
c
k
r
u
t
o
r
i
a
l
.
c
o
m
Previous Post
Next Post

post written by: