×

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

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Java Editors

A straightforward text editor may be used to create Java applications. However, a Java integrated programming environment (IDE) enables the software developer to create programs more quickly. An IDE offers...

4 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.