How to convert character array to string in Java

Read Time:6 Minute, 28 Second

Table of Contents

A string is defined as a collection of characters. A character array differs from a string in that the string is terminated with the special character “.” A string is transformed from a character array and vice versa. We’ll consider converting a character array to a string in this article.

Methods:

  • Using copyOf() method of Arrays class
  • Using StringBuilder class
  • Using valueOf() method of String class
  • Using copyValueOf() method of String class
  • Using Collectors in Streams
  • Using String class Constructor

Let us examine each of the methods in detail and implement them using a clean Java program.

Converting character array to string in Java

Function 1: Using the Array class’s copyOf() method

The String constructor accepts the provided character as an argument. Arrays are used to copy the contents of the character array by default. The Arrays class has a copyOf() function.

Example: A program for Converting Character Array to String in Java

SUGGESTED READ

Method 2: Making use of the StringBuilder class

What if we wanted to make a String out of a collection of char arrays? Then we can create a StringBuilder object and utilize its append(char[]) function to join all of the elements together.

The StringBuilder class is also used to transform a character array into a string. The idea is to cycle through the character array and attach each character to the end of the string because a StringBuilder is a changeable class. Finally, the string contains the characters’ string form. Later, we’ll utilize the toString() method to retrieve its String representation.

The StringBuilder class’s append() method appends the char[] array’s string representation.

It parses the to-be-appended parameter str. This object is returned as a reference. This function works similar to String.valueOf(char[]), except that the characters of that string are appended to this character sequence.

The syntax is as follows:

SUGGESTED READ

The toString() method

The StringBuilder class’s toString() method returns a string representing the sequence’s data. It creates a new String object and sets its initial value to the character sequence. Any changes we make to the char[] array do not affect the freshly formed string.

The syntax is as follows:

To convert the char[] array to string in the following example, we utilized the StringBuilder class’s append() and toString() methods.

Example: Program for Converting Character Array to String in Java

Example: String Builder

We may make the following code even more efficient by creating a StringBuilder with the required length.

Example: Char Array to String Using StringBuilder

Function 3: Using the String class’s valueOf() method

The valueOf() function of the String class is also used to convert a character array to a string.

SUGGESTED READ

This method automatically changes the character array to a format that displays the whole value of the characters in the array. This function converts a string from an int, float, double, char, boolean, or even an object. We’ll accomplish our goal by transforming our character array into a string.

In the following example, we’ve generated a char[] array named charArray. After that, we used the String class’s valueOf() method to parse a char[] charArray into it. The latter returns the character sequence we specified in the parameter.

Example: A program for Converting a Character Array to String in Java

In the subsequent section, we look at another example where the valueOf() method converts a char array to a string.

The first step is creating a character array as follows:

SUGGESTED READ

Then the valueOf() method will take over to convert the entire array into a string, as shown below.

We then put all of these together as a complete function called, CodeunderscoredValueOf() as illustrated below.

Function 4: Using the String class’s copyValueOf() method

It functions like the valueOf() method. The String class’s copyValueOf() method is also a static method. A char[] array is also parsed. In addition, it returns the character sequence (String) we specified in the parameter.

The character array’s contents are copied and then edited without impacting the string to be returned. This approach also allows us to convert the character array to string, as seen in the following example.

Example: Program for Converting a Character Array to String in Java

SUGGESTED READ

Let’s look at another example where the copyValueOf() method is used to convert a char array to a string.

String#copyValueOf is a method that is semantically equivalent to the valueOf() method, but it was only helpful in the early Java releases. The copyValueOf() function is obsolete as of today, and we don’t advocate utilizing it.

Function 5: Using Collectors in Streams in Java

With the advent of streams in java8, we immediately use Collectors in streams to alter our character input array members and then use the joining() method to return a single string, which we then print.

Example: Program for Converting a Character array to String in Java

We can open a stream across an array of type T using the Arrays.stream(T[] object) method. Subsequently, we can use the Collectors.joining() function to create a String with a Character array.

The disadvantage of this technique is that we are executing valueOf() on each Character element, which will be slow.

SUGGESTED READ

Example: Using String object and Using valueOf method

This example shows how to convert a char array to a String using both the valueOf() method of String class and creating String object by passing array name to the constructor. We have a char array ch, and we have used the char array to construct two strings, str, and str1.

Guava Joiner (Common Base)

Let’s pretend the string we’re trying to make is a delimited string. Guava provides us with a useful method:

It’s worth noting that the join() method only accepts a Character array, not a raw char array.

Constructing a String Class Constructor

A constructor in the String class takes a char[] array as an argument and allocates a new String. It denotes the order in which the characters appear (string). The freshly formed string remains unchanged if we change the char[] array.

SUGGESTED READ

The syntax is as follows:

Where char[] is the string’s starting value, subsequently, we’ve constructed a character array called chVal in the example below. After that, we developed a String constructor that takes the char[] array chVal as a parameter and parsed it. The char[] array is converted to a string.

Conclusion

This article explored converting a character array to its String representation in Java. To convert a char array to a string in Java, use the valueOf() function. The valueOf() method is a String class static method that you may use to convert a char[] array to a string. The method parses a char[] array as an argument. Then it returns a newly allocated string with the same sequence of characters as the character array. The freshly formed string remains unchanged if we change the char[] array.

In addition, the copyValueOf() method can also be used to represent the character sequence in the array given. It returns a string containing the characters from the character array supplied.

The constructor of the String class is overloaded in various places. String(char[]) is a constructor that takes a character array as an argument. It then creates a new string to reflect the character sequence provided in the character array parameter.

SUGGESTED READ

Source: https://www.codeunderscored.com/how-to-convert-character-array-to-string-in-java/

Tag Cloud

Java Java Logical Programs OTP Generation in Java python Recursion youtube video ASCII Upper and Lower Case blockchain javascript graph learn to code software development Successful Software Engineers breadth first search Java Array Programs Java Programs Uncategorized android ios programming kotlin web-development django data sql cybersecurity database swiftui serverless aws swift rust react background-position gradients loader mask grid nth-child pseudo elements indieweb WordPress Print Array without brackets C++ factorial Java String Programs Final Keyword Static Variable Axie Infinity Cryptokitties NFT games tool inserting MISC Tips Codes python code python projects python3 system info python project Bigginers How to Do Integrations Payment Gateways PHP checkout page in php Implement stripe payment gateway in Step by step in PHP integrate stripe gatway in php mysql payment gateway integration in php step by step payment gateway integration in php step by step with source code payment gateway integration in website PHP Integrate Stripe Payment Gateway Tutorial PHP shopping cart checkout code shopping cart in php stripe php checkout PHP/MySQL/JSON best international payment gateway does google pay accept international payments how to accept international payments in india paytm payment gateway razorpay codeigniter github razorpay custom checkout github razorpay get payment details razorpay integration in codeigniter github razorpay international payments Razorpay payment gateway integration in CodeIgniter razorpay payment gateway integration in php code Razorpay payment gateway integration with PHP and CodeIgniter Razorpay payment gateway setup in CodeIgniter Library & Frameworks Tips & Tricks UI/UX & Front-end coding birds online html code for google sign in login with google account in PHP login with google account using javascript login with google account using javascript codeigniter login with google account using php login with google account using php source code
Convert List to Array in Java Previous post Convert List to Array in Java
Next post How to convert an integer to a string in Java

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.