Convert Character Array to String in Java

By IncludeHelp Last updated : January 30, 2024

Given a character array and we have to convert it to the string in Java.

Converting Character Array to String

There are two ways to convert a character array to string in Java:

  1. Using String.valueOf(char[]) method
  2. By creating a new string with character array

Convert Character Array to String using String.valueOf() Method

valueOf() method is a String class method, it accepts a character array and returns the string.

Example

public class Main {
  public static void main(String[] args) {
    char[] charArray = {'I', 'n', 'c', 'l', 'u', 'd', 'e', 'h', 'e', 'l', 'p'};

    String str = "";

    //converting from char[] to string
    str = String.valueOf(charArray);

    //printing value 
    System.out.println("str = " + str);
  }
}

Output

str = Includehelp

Convert Character Array to String By Using New String

We can create a new string with the character array.

Syntax

String str_var = new String(char[]);

Example

public class Main {
  public static void main(String[] args) {
    char[] charArray = {'I', 'n', 'c', 'l', 'u', 'd', 'e', 'h', 'e', 'l', 'p'};

    String str = "";

    //creating a new string  from char[]
    str = new String(charArray);

    //printing value 
    System.out.println("str = " + str);
  }
}

Output

str = Includehelp

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.