446

I have a char array:

char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};

My current solution is to do

String b = new String(a);

But surely there is a better way of doing this?

Sam
  • 7,252
  • 16
  • 46
  • 65
chutsu
  • 13,612
  • 19
  • 65
  • 86
  • 173
    Why do think that there is a better way? And don't call me Shirley. :) – Hovercraft Full Of Eels Oct 04 '11 at 23:24
  • 1
    Because I always associate making new variables such as the above to have a slight over head during runtime. Like if I put the above line to convert a char array to a string into a for loop for example, to me it doesn't quite look right. And yes I'm a bit of a perfectionist. . . – chutsu Oct 04 '11 at 23:27
  • 2
    If you have a lot of these guys, say an array or collection of char[], then perhaps you would append the char arrays to a StringBuffer, but for a String here or there, what you've posted is what most use. – Hovercraft Full Of Eels Oct 04 '11 at 23:29
  • If you are looking for a way to avoid copying the char[] then there isn't one. Otherwise you could subvert String's immutability. – Paul Cager Oct 04 '11 at 23:33
  • 14
    "making new variables" incurs zero overhead. A variable is a name used to refer to a value, and the name itself isn't present anywhere in memory at runtime (at least, not in a language like Java where reflection is fairly limited). The "overhead" comes from constructing a new **value**, and there is no way around that in your case, considering that your problem is "construct this value". You cannot cause the char array to magically transmogrify into a String. You **can** arrange for the original char array to be garbage-collected after the String is created. – Karl Knechtel Oct 04 '11 at 23:35
  • How efficient is `String b = new String(a);`? – Soubriquet Jan 16 '15 at 21:19
  • Using the `String` constructor in your example means the string object will not be in the string pool. – Ammar Samater Oct 30 '17 at 12:48

14 Answers14

230

No, that solution is absolutely correct and very minimal.

Note however, that this is a very unusual situation: Because String is handled specially in Java, even "foo" is actually a String. So the need for splitting a String into individual chars and join them back is not required in normal code.

Compare this to C/C++ where "foo" you have a bundle of chars terminated by a zero byte on one side and string on the other side and many conversions between them due do legacy methods.

A.H.
  • 63,967
  • 15
  • 92
  • 126
158

String text = String.copyValueOf(data);

or

String text = String.valueOf(data);

is arguably better (encapsulates the new String call).

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
David Titarenco
  • 32,662
  • 13
  • 66
  • 111
  • 7
    Both methods call `String(char[])` or a variant of that. And the copy part is done inside `String(char[])`. This leaves no benefit to a direct call besides symmetry with the other `valueOf` methods. – A.H. Oct 04 '11 at 23:35
  • 1
    _static_ and _more OOP_ is a contradiction of terms. Anything declared _static_ is not part an object or its behaviour and hence not object oriented. Besides of this - if there would be any chance that the implementation of `String` will be changed and/or enhanced in an incompatible way or several competing implementations can be chosen at runtime, then a _static_ factory method makes sense. This will not happen with such a low level thing as `String`. Therefore my premise is: Use the smallest hammer suitable, not the largest one available. – A.H. Oct 04 '11 at 23:49
  • @A.H. I don't know about that. String gave way to StringBuffer which gave way to StringBuilder. I bet StringBuffer proponents said the same thing then, and now have to refactor code to use StringBuilder. – corsiKa Mar 15 '13 at 15:45
  • @corsiKa: StringBuffer might have been superseded by StringBuilder. This is how I understand "give way to". But String has _not_ been superseded by any of them. And never will. The advantage of immutable types (which String effectively is) is to good and to important. Also StringBuilder and -Buffer can coexist quite nicely. Two different String representations are a completely different beast. I have a _strong_ doubt that the existing APIs and language tweaks would benefit from that. – A.H. Mar 15 '13 at 15:59
  • 1
    @A.H. The fact that they had to create the `CharSequence` interface shows how flawed your "wont happen with low level stuff like string" is - they don't change what goes on in string because they tied themselves to it early on, and now they wish they wouldn't have. – corsiKa Mar 15 '13 at 17:01
  • 1
    @corsiKa I did not say, that the String API is all good and golden. Only that it won't change in an incompatible way and that the class itself and its constructors won't go anywhere. :-) – A.H. Mar 15 '13 at 17:58
  • In some situations, the method `String.valueOf(char[] data, int offset, int count)` is useful. One example is the `characters()` method in the SAX API for processing XML. – rakensi Feb 23 '15 at 13:58
39

This will convert char array back to string:

char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
Billz
  • 7,879
  • 7
  • 33
  • 35
22
String str = "wwwwww3333dfevvv";
char[] c = str.toCharArray();

Now to convert character array into String , there are two ways.

Arrays.toString(c);

Returns the string [w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v].

And:

String.valueOf(c)

Returns the string wwwwww3333dfevvv.

In Summary: pay attention to Arrays.toString(c), because you'll get "[w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v]" instead of "wwwwww3333dfevvv".

Teocci
  • 7,189
  • 1
  • 50
  • 48
AalekhG
  • 361
  • 3
  • 8
9

A String in java is merely an object around an array of chars. Hence a

char[]

is identical to an unboxed String with the same characters. By creating a new String from your array of characters

new String(char[])

you are essentially telling the compiler to autobox a String object around your array of characters.

Nathan Meyer
  • 409
  • 1
  • 6
  • 13
4

Just use String.value of like below;

  private static void h() {

        String helloWorld = "helloWorld";
        System.out.println(helloWorld);

        char [] charArr = helloWorld.toCharArray();

        System.out.println(String.valueOf(charArr));
    }
Akash Yellappa
  • 2,126
  • 28
  • 21
2
package naresh.java;

public class TestDoubleString {

    public static void main(String args[]){
        String str="abbcccddef";    
        char charArray[]=str.toCharArray();
        int len=charArray.length;

        for(int i=0;i<len;i++){
            //if i th one and i+1 th character are same then update the charArray
            try{
                if(charArray[i]==charArray[i+1]){
                    charArray[i]='0';                   
                }}
                catch(Exception e){
                    System.out.println("Exception");
                }
        }//finally printing final character string
        for(int k=0;k<charArray.length;k++){
            if(charArray[k]!='0'){
                System.out.println(charArray[k]);
            }       }
    }
}
baikho
  • 5,203
  • 4
  • 40
  • 47
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – baikho Aug 04 '17 at 20:29
1
 //Given Character Array 
  char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};


    //Converting Character Array to String using String funtion     
    System.out.println(String.valueOf(a));
    //OUTPUT : hello world

Converting any given Array type to String using Java 8 Stream function

String stringValue = 
Arrays.stream(new char[][]{a}).map(String::valueOf).collect(Collectors.joining());
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
1

Try to use java.util.Arrays. This module has a variety of useful methods that could be used related to Arrays.

Arrays.toString(your_array_here[]);
palaѕн
  • 72,112
  • 17
  • 116
  • 136
Adzz
  • 77
  • 1
  • 6
-1

Try this

Arrays.toString(array)
Jess
  • 85
  • 12
-1
String output = new String(charArray);

Where charArray is the character array and output is your character array converted to the string.

Anubhav
  • 1,984
  • 22
  • 17
-3

Try this:

CharSequence[] charArray = {"a","b","c"};

for (int i = 0; i < charArray.length; i++){
    String str = charArray.toString().join("", charArray[i]);
    System.out.print(str);
}
Ben Leitner
  • 1,532
  • 1
  • 12
  • 33
Curtis H
  • 11
  • 8
-4

You can also use StringBuilder class

String b = new StringBuilder(a).toString();

Use of String or StringBuilder varies with your method requirements.

David Medenjak
  • 33,993
  • 14
  • 106
  • 134
-12

1 alternate way is to do:

String b = a + "";
Patrick Kostjens
  • 5,065
  • 6
  • 29
  • 46
  • 3
    this is wrong as it assumes that `toString` works correctly on `char[]`. It might work on some specific vendors and versions of the JVM. – fommil Apr 18 '14 at 15:37
  • 3
    Because String class is immutable, this will cause two operations to be performed: toString() call on `a` and creation of another String object that concatenates with `a.toString()` and `""` – Alpay Jun 06 '14 at 12:34