While writing unit tests for a function returning boolean
that takes two String
s, 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.
We can convert char to String in java using String. valueOf(char) method of String class and Character. toString(char) method of Character class.
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.
char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With