Convert Char Array to String in Java

When working with character arrays (char []) in Java, you often want to convert it to string. In this post, we’ll see two techniques of coverting character arrays to strings in Java.

  1. Using String.valueOf(…) method
  2. Using String class Constructor

1. Using String.valueOf(…) method

This is my preferred approach. It’s easy to remember because valueOf(...) method is widely used to convert between types. In this case, String.valueOf(char [] data) takes a char [] array as an argument and returns its string representation. The returned string is “safe”: it can be modified and won’t affect the character array. Let’s look at an example.

package com.codeahoy.ex;

public class Main {
    public static void main(String[] args) {
        char[] charArray = { 'G', 'o', 'o', 'g', 'l', 'e' };

        // Convert char [] to String using valueOf
        String str = String.valueOf(charArray);

        System.out.println(str);
    }
}

Output

Google

There’s also another method called copyValueOf(char [] data) which is equivalent to valueOf(...). I think it’s there for backwards compatibility reasons and will advice that you prefer valueOf(...) over it.

2. Using String class Constructor

String class in Java has a overloaded constructor which takes char [] array as argument. The String is created using the char [] array and is “safe”, that is, subsequent modification of the string or char [] array doesn’t affect each other. Let’s look at an example.

package com.codeahoy.ex;

public class Main {
    public static void main(String[] args) {
        char[] charArray = { 'C', 'o', 'd', 'e', 'A', 'h', 'o', 'y' };

        // Convert char [] to String
        String str = new String(charArray);

        System.out.println(str);
    }
}

Output

CodeAhoy

There are other ways of converting character array to string in Java but these two are the ones that are most commonly used in practice. Until next time.

Please leave your comments below and like on Facebook or follow on Twitter to stay up-to-date.

comments powered by Disqus