How to Convert Character Array to String in Java?
Last Updated :
20 Dec, 2024
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character "\0". A character array can be converted to a string and vice versa. In this article, we will discuss how to convert a character array to a string.
Examples:
Input 1 : char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's' }
Output 1 : "geeksforgeeks"
Input 2 : char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' }
Output 2 : "coding"
Program:
Java
// Convert Character Array to String
// Using copyOf() method ofArrays() Class
import java.util.*;
class GFG {
// To convert a character
// array to a string using the constructor
public static String toString(char[] a){
String str = new String(a);
return str;
}
public static void main(String args[])
{
char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' };
System.out.println(toString(s));
}
}
Here we are using copyOf() method of Array class . The given character can be passed into the String constructor. By default, the character array contents are copied using the Arrays.copyOf() method present in the Arrays class.
Other Methods to Convert Character Array to String
- Using StringBuilder class
- Using valueOf() method of String class
- Using copyValueOf() method of String class
- Using Collectors in Streams
1. Using StringBuilder class
Another way to convert a character array to a string is to use the StringBuilder class. Since a StringBuilder is a mutable class, therefore, the idea is to iterate through the character array and append each character at the end of the string. Finally, the string contains the string form of the characters.
Example:
Java
// Convert Character Array to String
// Using StringBuilder Class
import java.util.*;
public class GFG {
// To convert a character array to a string
// using the StringBuilder class
public static String toString(char[] a){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length; i++)
sb.append(a[i]);
return sb.toString();
}
public static void main(String args[]){
char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' };
System.out.println(toString(s));
}
}
2. Using valueOf() method of String class
Another way to convert a character array to a string is to use the valueOf() method present in the String class. This method inherently converts the character array to a format where the entire value of the characters present in the array is displayed. This method generally converts int, float, double, char, boolean, and even object to a string. Here we will achieve the goal by converting our character array to string.
Example:
Java
// Convert Character Array to String
// Using valueOf() method
import java.util.*;
class GFG {
// To convert a character array to string
// using the valueOf() method
public static String toString(char[] a)
{
String string = String.valueOf(a);
return string;
}
// Main driver method
public static void main(String args[])
{
char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' };
System.out.println(toString(s));
}
}
3. Using copyValueOf() method of String class
Using copyValueOf() method of String class to use contents from the character array that are copied and subsequently modified without affecting the string to be returned, hence this method also enables us to convert the character array to a string which can be perceived even better from the example provided below as follows.
Example:
Java
// Convert Character Array to String
// Using copyValueOf() method
import java.util.*;
class GFG {
public static void main(String[] args)
{
char[] arr = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' };
// Storing it in a string
// using copyValueOf() over string
String str = String.copyValueOf(arr);
System.out.print(str);
}
}
4. Using Collectors in Streams
With the introduction of streams in java8, we straight away use Collectors in streams to modify our character input array elements and later uses joining() method and return a single string and print it.
Example:
Java
// Convert a Character array to String
// Using Collectors in Streams in Java8
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Main {
public static void main(String[] args)
{
char[] charr = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' };
// Using collectors to collect array elements and
// later using joining method to return a single
// string
String str = Stream.of(charr)
.map(arr -> new String(arr))
.collect(Collectors.joining());
System.out.println(str);
}
}
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read