Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the correct way to convert a char to a String in Java? [duplicate]

Tags:

While writing unit tests for a function returning boolean that takes two Strings, and I needed to test every character of the alphabet ('a'-'z') in sequence as one of the parameters, one-by-one, so I wrote this to do that:

for(char c = 'a'; c <= 'z'; c++) {     assertTrue(MyClass.MyFunction(testSubject, new String(c)); }  

I would have thought this was permissible, but it wasn't, so I just did it like this instead:

for(char c = 'a'; c <= 'z'; c++) {     assertTrue(MyClass.MyFunction(testSubject, ((Character) c).toString()); }  

Is this a reliable method to convert a char to a String in Java? Is it the preferred way? I don't know a whole lot about Java so would like some clarification on this.

like image 226
Govind Parmar Avatar asked Apr 28 '20 00:04

Govind Parmar


People also ask

How do I convert a char to a string in Java?

We can convert char to String in java using String. valueOf(char) method of String class and Character. toString(char) method of Character class.

Can char convert to double?

The C library function double strtod(const char *str, char **endptr) converts the string pointed to by the argument str to a floating-point number (type double). If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.

How do you make a char array into a string?

char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);

How do you change a character in a string?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.


1 Answers

The shortest solution:

char c = 'a'; String s = "" + c; 

The cleanest (and probably most efficient1) solutions:

char c = 'a';  String s1 = String.valueOf(c); // or String s2 = Character.toString(c); 

Compared to your approach, the above prevents the overhead of having to box the primitive into a Character object.


1 The slight inefficiency of the string concatenation in the first approach might be optimized away by the compiler or runtime, so one (if one were so inclined) would really have to run a micro-benchmark to determine actual performance. Micro-optimizations like this are rarely worth the effort, and relying on concatenation to force string conversion just doesn't look very nice.

like image 74
Robby Cornelissen Avatar answered Nov 02 '22 18:11

Robby Cornelissen