Как перевести char в string java
Перейти к содержимому

Как перевести char в string java

  • автор:

How to Convert Char to String in Java?

In Java char is a primitive data type and String is an object that represents a sequence of char values. There are multiple ways to convert a char to string in Java. Some of the key ways to convert char to string in Java are:

  • String.valueOf() method
  • Character.toString()
  • Concatenation of a string with a char

String.valueOf() and Character.toString() are the most used methods to convert char to string in Java.

Scope

This article covers below topics :

  • char and string and their various methods for the conversion of char to string in Java.
  • This article also contains an example of the conversion of a string to a char array in Java.

This article doesn't explain the differences between a char array and a string.

Introduction

In Java, char is a primitive data type that is used to store a single character. Single quotes are used to surround a char value like, 'A', 'B', etc. While the string is an object that represents a series of char values. Doubles quotes are used to surround a string like, "java". This string contains a series of characters 'j', 'a', 'v', and 'a'.

There are multiple ways to convert char to string in Java. Let's understand them one by one.

Java char to string using String.valueOf() method

The String.valueOf() method is used to convert different types of values to string . This method accepts different kinds of values such as char , int , boolean , double , float , etc.

For our article, we will use this method to convert char to string in Java. We will pass a char value and the method will return a string version of the char value.

Syntax:

Example: To convert char to string using String.valueOf() method.

Output:

Java char to string using Character.toString() method

Second method to convert char to string in Java is Character.toString() . For converting a char to string, we will pass the char to the method as an argument .

Calling the method by passing a char as an argument.

Syntax:

Example: To convert char to string using toString() method.

Output:

Java char to string using Concatenation of strings

Another way to convert char to string in Java is by concatenating the char to an empty string. Let's have an example to understand this.

Output:

Convert string to char Array

In Java, we can use the toCharArray() method to convert a string to char Array.

Syntax:

Example To convert a string to char array using the toCharArray() method.

Convert char to String in Java

Convert char to String in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Sometimes we have to convert char to String in java program. Here we will look into different methods you can convert character to string in java. We will also learn how to convert char array to String using different methods.

Convert char to String Java

convert char to string java Here is a simple program showing different ways to convert char to string in java.

Let’s look at these methods one by one.

String.valueOf(char c)

This is the most efficient method to convert char to string. You should always use this method and this is the recommended way to convert character to string in java program.

Character.toString©

This method internally calls String.valueOf(c) , so there is no difference between this one. You can use this too if you are already using Character class in your code.

new Character©.toString();

This is another way, however not recommended because we are creating a Character unnecessarily.

String concatenation

str = "" + c; is the worst way to convert char to string because internally it’s done by new StringBuilder().append("").append(c).toString() that is slow in performance. Let’s look at the two methods to convert char array to string in java program.

String constructor

You can use String(char[] value) constructor to convert char array to string. This is the recommended way.

String.valueOf(char[] data)

String valueOf method is overloaded and there is one that accepts character array. Internally this method calls the String constructor, so it’s same as above method. That’s all for converting char to string and char array to string in java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Overview

Anshika Singh

In this quick tutorial, we'll cover various ways to convert a character array to a String in Java.

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.

A String in java is merely an object around an array of chars. Hence a char is identical to an unboxed String with the same characters. By creating a new String from your array of characters you are essentially telling the compiler to autobox a String object around your array of characters.

There are five ways to convert char array to string in Java:
1-String Class Constructor

2- String Builder Class

3- Value of() Method

4-Java 8 Streams

5-Guava Common Base Joiner

1- STRING CLASS CONSTRUCTOR

The given character can be passed into the String constructor.The String class has a constructor that accepts a char array as an argument:

public void whenStringConstructor_thenOK() <

String string = new String(charArray);

This is one of the easiest ways of converting a char array to a String. It internally invokes String#valueOf to create a String object.

2- STRING BUILDER 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.

// Function to convert a character

// array to a string using the

public void whenStringBuilder_thenOK() <

StringBuilder sb = new StringBuilder();

for (char[] subArray : arrayOfCharArray) <

We can further optimize the above code by instantiating the StringBuilder of the exact length we need.

3- VALUE OF() METHOD

The valueOf() method is a static method of the String class that is also used to convert char[] array to string. The method parses a char[] array as a parameter. It returns a newly allocated string that represents the same sequence of characters contained in the character array. If we do any modification in the char[] array, the newly created string remains the same.

public class CharArrayToStringExample

public static void main(String args[])

//constructor of the String class

String str = new String();

//invoking valueOf() method of the String class

String string = str.valueOf(chars);

//prints the string

A- COPY VALUE OF() METHOD

It is similar to the valueOf() method. The copyValueOf() method is also a static method of the String class.

String#copyValueOf is another method that's semantically equivalent to the valueOf() method but was of any significance only in a first few Java releases. As of today, the copyValueOf() method is redundant and we don't recommend using it.

4- JAVA 8 STREAMS

With Arrays.stream(T[] object) method, we can open a stream over an array of type T.

Considering we have a Character array, we can use the Collectors.joining() operation to form a String instance:

public void whenStreamCollectors_thenOK() <

Stream<Character> charStream = Arrays.stream(charArray);

String string = charStream.map(String::valueOf).collect(Collectors.joining());

The caveat with this approach is that we are invoking the valueOf() over each Character element and so it'll be pretty slow.

5- GUAVA COMMON BASE JOINER

Let's say though that the string we need to create is a delimited string. Guava gives us a handy method:

public void whenGuavaCommonBaseJoiners_thenOK() <

String string = Joiner.on("|").join(charArray);

The join() method will only accept a Character array and not the primitive char array.
Please note that in all approaches discussed above, the contents of the character array are copied. That means that any subsequent modification of the character array will not affect the returned string.

How to convert a char to a String?

I have a char and I need a String . How do I convert from one to the other?

Rakete1111's user avatar

Landon Kuhn's user avatar

13 Answers 13

You can use Character.toString(char) . Note that this method simply returns a call to String.valueOf(char) , which also works.

As others have noted, string concatenation works as a shortcut as well:

But this compiles down to:

which is less efficient because the StringBuilder is backed by a char[] (over-allocated by StringBuilder() to 16 ), only for that array to be defensively copied by the resulting String .

String.valueOf(char) «gets in the back door» by wrapping the char in a single-element array and passing it to the package private constructor String(char[], boolean) , which avoids the array copy.

I’ve got of the following five six methods to do it.

String.valueOf(char[] value) invokes new String(char[] value) , which in turn sets the value char array.

On the other hand String.valueOf(char value) invokes the following package private constructor.

Source code from String.java in Java 8 source code

Hence String.valueOf(char) seems to be most efficient method, in terms of both memory and speed, for converting char to String .

Below are various ways to convert to char c to String s (in decreasing order of speed and efficiency)

Use any of the following:

Use the Character.toString() method like so:

byxor's user avatar

As @WarFox stated — there are 6 methods to convert char to string. However, the fastest one would be via concatenation, despite answers above stating that it is String.valueOf . Here is benchmark that proves that:

As you can see, the fastest one would be c + «» or «» + c ;

This performance difference is due to -XX:+OptimizeStringConcat optimization. You can read about it here.

Dmitriy Dumanskiy's user avatar

Try this: Character.toString(aChar) or just this: aChar + «»

Óscar López's user avatar

We have various ways to convert a char to String . One way is to make use of static method toString() in Character class:

Actually this toString method internally makes use of valueOf method from String class which makes use of char array:

So second way is to use this directly:

This valueOf method in String class makes use of char array:

So the third way is to make use of an anonymous array to wrap a single character and then passing it to String constructor:

The fourth way is to make use of concatenation:

This will actually make use of append method from StringBuilder class which is actually preferred when we are doing concatenation in a loop.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *