×

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string can be transformed from a character array and vice versa. We'll look how to make a character array from a string in this tutorial.

Illustrations

Input 1: char s[] = { ‘j’, ‘a’, ‘v’, ‘a’, ‘T’, ‘p’, ‘o’, ‘i’, ‘n’, ‘t’, ‘ ’ ,‘t’, ‘u’, ‘t’ , ‘o’ , ‘r’ , ‘i’ , ‘a’ , ‘l’}

Output 1: “javaTpoint tutorial”

Input 2: char s[] = { ‘j’, ‘a’, ‘v’, ‘a’, ‘ ’ , ‘c’, ‘o’ , ‘d’ , ‘e’ , ‘s’ }

Output 2: “javacodes”

Approaches

  1. Using the Arrays class's copyOf() function
  2. Making use of the StringBuilder class
  3. Using the String class's function valueOf() 
  4. Using the String class's function copyValueOf()
  5. In Streams, Using Collectors

Let us now go through each of the methods in detail, as well as how to implement them using a Java program.

Approach 1: Using the Arrays class's copyOf() function

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

For instance:

// Converting a Character Array to a String in Java
// Using the Arrays class's copyOf() function
// Importing the necessary classes
import java.util.*;
// Main class
class JTP{
//Approach 1
// Using the function Object()  to convert a character array to a string
public static String toString(char[] ch)
 {
  // constructing a string object
 String string = new string (ch);
 return string ;
}
// Approach 2
// Method of the main driver
Public static void main(string args[] )
{
  // Declaring and initializing input character array
   char st[] = { ‘j’  , ‘a’, ‘v’ , ‘a’ , ‘T’ , ‘p’ , ‘o’ , ‘i’  , ‘n’, ‘t’ , ‘ ’ ,‘t’ , ‘u’ , ‘t’ , ‘o’ , ‘r’ , ‘i’ , ‘a’ , ‘l’} ;
 // To a character array, print the relevant string.
System.out.println( toString ( st ) );
}
}

Output:

javaTpoint tutorial

Approach 2: Making use of the StringBuilder class

The StringBuilder class can also be used into transform a character array to 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. Lastly, the string contains the characters' string form.

For instance:

//Converting a Character Array to a String in Java
// Making use of the StringBuilder class
 
// Importing the necessary classes
importjava.util.*;
 
// Main class
publicclassGFG {
 
    // Approach 1
    // Using the StringBuilder class to convert a character array to a string
    publicstaticString toString(char[] ch)
    {
        // Creating a String class object
        StringBuilder SB = newStringBuilder();
 
        // Using the append() function to create a string
for(intj = 0; j<ch.length; j++) {
            SB.append(ch[j]);
        }
 
        ReturnSB.toString();
    }
 
    // Approach 2
    // Method of the main driver
    publicstaticvoidmain(String args[])
    {
 
        // Declaring and initializing input character array
        charsh[] = { ‘j’  , ‘a’, ‘v’ , ‘a’ , ‘T’ , ‘p’ , ‘o’ , ‘i’  , ‘n’, ‘t’ , ‘ ’ ,‘t’ , ‘u’ , ‘t’ , ‘o’ , ‘r’ , ‘i’ , ‘a’ , ‘l’};
 
        // To a character array, print the relevant string.
        System.out.println(toString(sh));
    }
   }

Output:

javaTpoint tutorial

Approach 3: Using the String class's function valueOf() 

The valueOf()  function of the String class can also be used to convert a character array to a string. This method automatically changes the character array to a layout that displays the whole value of the characters in the array. This method converts a string from an int, float, double, char, Boolean, or even an object. We'll accomplish our goal here by transforming our character array into a string.

For instance:

// Converting a Character Array to a String in Java
// Using the String class' function valueOf() 
 
// Importing the necessary classes
importjava.util.*;
 
// Main class
classJTP {
 
    // Approach 1
    // The function valueOf()  is used to convert a character array to a string.
    publicstaticString toString(char[] ch)
    {
        // Creating a String class object
        String string = String.valueOf(ch);


returnstring;
    }
 
    // Approach 2
    // Method of the main driver
    publicstaticvoidmain(String args[])
    {
 
        // The input character array is declared and initialised.
        charsh[] ={ ‘j’  , ‘a’, ‘v’ , ‘a’ , ‘T’ , ‘p’ , ‘o’ , ‘i’  , ‘n’, ‘t’ , ‘ ’ ,‘t’ , ‘u’ , ‘t’ , ‘o’ , ‘r’ , ‘i’ , ‘a’ , ‘l’};


 
        // To a character array, print the relevant string.
        System.out.println(toString(sh));
    }
}

Output:

javaTpoint tutorial

Approach 4: Using the String class's function copyValueOf()

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

For instance:

//Converting a Character Array to a String in Java
// Using the String class' function copyValueOf()
 
// String class is being imported.
importjava.util.*;
 
// Main class
classJTP{
 
    // Method of the main driver


    publicstaticvoidmain(String[] args)
    {
        // The input character array is declared and initialised.
        char[] arrr = { ‘j’  , ‘a’, ‘v’ , ‘a’ , ‘T’ , ‘p’ , ‘o’ , ‘i’  , ‘n’, ‘t’ , ‘ ’ ,‘t’ , ‘u’ , ‘t’ , ‘o’ , ‘r’ , ‘i’ , ‘a’ , ‘l’};
 
        // Keeping it in a string
        // over a string with copyValueOf()
        String strr = String.copyValueOf(arrr);
 
        // To a character array, print the relevant string.


        System.out.print(strr);
    }
}

Output:

javaTpoint tutorial

Approach 5: In Streams, Using Collectors

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

For instance:

// Converting a Character Array to a String in Java
// In Streams, Using Collectors, in java8
 
// Collectos and Stream classes are imported.
// from the package java.util.stream
importjava.util.stream.Collectors;
importjava.util.stream.Stream;
 
// Main class of this code
classJTP{
 
    // Method of the main driver
    publicstaticvoidmain(String[] args)
    {
 
        // Character array for custom input
 char[] character = { ‘j’  , ‘a’, ‘v’ , ‘a’ , ‘T’ , ‘p’ , ‘o’ , ‘i’  , ‘n’, ‘t’ , ‘ ’ ,‘t’ , ‘u’ , ‘t’ , ‘o’ , ‘r’ , ‘i’ , ‘a’ , ‘l’};
 
        // Collectors are used to collect array elements, and then the joining function is used to return a single string.


        String strr = Stream.of(character)
                         .map(arrr ->newString(arrr))
                         .collect(Collectors.joining());
 
        // Creating a printout of the Collectors' stream
        System.out.println(strr);
    }
}

Output:

javaTpoint tutorial

Related Topics

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java Static Keyword

It can be either said that static declares the value to be the same, not only in the instance of a class but also as the whole. To declare a variable...

6 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.