How to convert Char array to String.
- String constructor
- String.valueOf()
- StringBuilder
- Stream
String constructor
Just create a String by passing a char array as an argument to the String constructor.
public void charArrayToString1() {
char[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
String str = new String(charArray);
System.out.println(str);
}
result
HelloWorld
String.valueOf()
If you pass a char array as an argument to String.valueOf()
, it creates a String.
public void charArrayToString2() {
char[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
String str = String.valueOf(charArray);
System.out.println(str);
}
result
HelloWorld
StringBuilder
You can also use StringBuilder.
public void charArrayToString3() {
char[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
StringBuilder sb = new StringBuilder();
for (char ch : charArray) {
sb.append(ch);
}
String str = sb.toString();
System.out.println(str);
}
result
HelloWorld
Stream
You can convert char to String with Stream, and combine Strings to make one String.
Character[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
Stream<Character> charStream = Arrays.stream(charArray);
String str = charStream.map(String::valueOf).collect(Collectors.joining());
System.out.println(str);
result
HelloWorld
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)