Converting Character Array to String in Java
Overview
A String can be defined as a data type representing ordered sequences of characters. Whereas a character array can be defined as an array where every index represents a character. A string can be converted into a character array and vice versa.
In Java, Strings are immutable whereas character arrays can be modified. Strings provide few utility functions such as charAt(), toUpperCase(), and toLowerCase() etc. that can be used to operate on strings, whereas a character array doesn’t have any inbuilt functions it is just a simple array containing characters at every index.
Methods of Conversion
A few methods to convert Character array to string are:
valueOf()
The valueOf method is present in the String class. This method can convert, float, array, object, int, double even boolean to string.
import java.util.*; Output: Program |
Collectors
Collectors is a final class that extends the Object class. Collectors can be used in streams to change input character array elements and by using joining() method a string can be returned.
import java.util.stream.Stream; Output: Program |
StringBuilder
The important characteristic of the StringBuilder class is that it is mutable so the logic is to iterate over the character array and append every character to the end of our string.
import java.util.*; Output: Program |
copyOf()
Using the String() constructor character can be passed and the character array contents are copied using the Array.copyOf() method.
import java.util.*; Output: Program |
copyValueOf()
The copyValueOf() method returns a String that is formed using a character array.
import java.util.*; Output: Program |