Java lang character to string java

6 ways to convert char to String in Java — Examples

If you have a char value like ‘a’ and you want to convert it into equivalent String like «a» then you can use any of the following 6 methods to convert a primitive char value into String in Java :

1) String concatenation
2) String.valueOf()
3) Character.toString()
4) Character wrapper class + toString
5) String constructor with a char array
6) String.valueOf(char [])

In this article, we will see examples of each approach and learn a little bit more about it. Actually, there is a lot of overlap between each method as some of them internally call String.valueOf() , which eventually calls to a String constructor which accepts char array and creates a String object containing primitive char value with length 1. Once you know, how they work internally, it easy to decide which one is more efficient for the purpose.

1.Char to String using concatenation in Java

This is the easiest way to convert a char to a String object in Java. All you need to do is concatenate a given character with an empty String, as shown in the following example:

char apple = 'a'; String aStr = "" + apple; System.out.println("char to String using concatenation : " + aStr); // a

Remark: This is the simplest method to convert a char value to a String but it’s less efficient and takes more memory than required. Compile translate String concatenation into the following code:

new StringBuilder().append(x).append("").toString();

This is less efficient because the StringBuilder is backed by a char[] of size 16, which is a waste of memory if you just converting one character. This array is then defensively copied by the resulting String

Читайте также:  Python numpy cheat sheet

2. Character to String using String.valueOf()

This is the standard way to convert a char primitive type into a String object. If you remember, we have already used the valueOf() method to convert String to int and String to double in Java. Here is the example of using this method to convert char to String:

char boy = 'b'; String bStr = String.valueOf(boy); System.out.println("char to String using String.valueOf() : " + bStr); // "b"

Remark: String.valueOf(char) is the most efficient method for converting char to String in Java because it just uses a character array of size one to wrap a given character and pass it to String constructor, as shown below (from JDK) :

3. Char to String conversion with Character.toString()

This is the third example to convert a char primitive value to a String object in Java. In this example, we have used Character.toString() method.

char cat = 'c'; String cStr = Character.toString(cat); System.out.println("char to String using Character.toString() : " + cStr);

Remark: This method returns a String object representing the given char. It returns a String of length one consisting solely of the specified char. Internally it also calls String.valueOf(char c) method.

Anyway, here is a nice summary of all the six ways to convert a char value to a String object in Java:

6 ways to convert a char to String object in Java

4. Char to String using a Character wrapper class

This is the 4th example of converting a char value to a String object in Java. This time, we will use java.lang.Character class, which is a wrapper for char primitive type.

char dog = 'd'; String dStr = new Character(dog).toString(); System.out.println("char to String using new Character() + toString : " + dStr);

Remark: This method returns the String equivalent of the Character object’s value of length 1. Internally this method wraps the encapsulated char value into a char array and passed it to the String.valueOf(char[]) method.

String constructor with a char array

Here is one more way to convert a char value to a String object in Java. In this example, we have wrapped the single character into a character array and passed it to a String constructor which accepts a char array as shown below:

String fStr = new String(new char[]'f'>); System.out.println("char to String using new String(char array) : " + fStr);


Remark: This is the method which is internally called by String.valueOf() method for char to String conversion. This constructor allocates a new String object to represent a sequence of characters passed via char array argument. The contents of the character array are defensively copied so that subsequent modification of the character array doesn’t affect the newly created String.

char to String using String.valueOf(char[])

This the sixth and last way to perform char to String conversion in our article, here is the sample code:

String gStr = String.valueOf(new char[]'g'>); System.out.println("char to String using String.valueOf(char array) : " + gStr);

Remark: String.valueOf() is overloaded to accept both char and char[] . Since the valueOf() method accepts a char, internally wrap that char into a character array it makes sense to use this overloaded method to directly pass a char array, which in turn passed to String constructor which accepts a character array.

That’s all about how to convert a char value to a String in Java. You can choose any of the above methods, which suits your test but remember, String concatenation is not efficient and can waste a lot of memories if used in the loop. String.valueOf() is more readable and efficient, so should be your default choice. All of the above methods internally use a new String(char[]) though.

Источник

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.

package com.journaldev.string; public class CharToStringJava < public static void main(String[] args) < // char to string char c = 'a'; String str = String.valueOf(c); // using Character class str = Character.toString(c); // another way str = new Character(c).toString(); // string concatenation - worst performance str = "" + c; // char array to string char[] ca = < 'a', 'b', 'c' >; str = String.valueOf(ca); // recommended way str = new String(ca); > > 

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();

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. Learn more about us

Источник

Class Character

The Character class wraps a value of the primitive type char in an object. An object of class Character contains a single field whose type is char .

In addition, this class provides a large number of static methods for determining a character’s category (lowercase letter, digit, etc.) and for converting characters from uppercase to lowercase and vice versa.

Unicode Conformance

The fields and methods of class Character are defined in terms of character information from the Unicode Standard, specifically the UnicodeData file that is part of the Unicode Character Database. This file specifies properties including name and category for every assigned Unicode code point or character range. The file is available from the Unicode Consortium at http://www.unicode.org.

Character information is based on the Unicode Standard, version 15.0.

The Java platform has supported different versions of the Unicode Standard over time. Upgrades to newer versions of the Unicode Standard occurred in the following Java releases, each indicating the new version:

Shows Java releases and supported Unicode versions
Java release Unicode version
Java SE 20 Unicode 15.0
Java SE 19 Unicode 14.0
Java SE 15 Unicode 13.0
Java SE 13 Unicode 12.1
Java SE 12 Unicode 11.0
Java SE 11 Unicode 10.0
Java SE 9 Unicode 8.0
Java SE 8 Unicode 6.2
Java SE 7 Unicode 6.0
Java SE 5.0 Unicode 4.0
Java SE 1.4 Unicode 3.0
JDK 1.1 Unicode 2.0
JDK 1.0.2 Unicode 1.1.5

Variations from these base Unicode versions, such as recognized appendixes, are documented elsewhere.

Unicode Character Representations

The char data type (and therefore the value that a Character object encapsulates) are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. The Unicode Standard has since been changed to allow for characters whose representation requires more than 16 bits. The range of legal code points is now U+0000 to U+10FFFF, known as Unicode scalar value. (Refer to the definition of the U+n notation in the Unicode Standard.)

The set of characters from U+0000 to U+FFFF is sometimes referred to as the Basic Multilingual Plane (BMP). Characters whose code points are greater than U+FFFF are called supplementary characters. The Java platform uses the UTF-16 representation in char arrays and in the String and StringBuffer classes. In this representation, supplementary characters are represented as a pair of char values, the first from the high-surrogates range, (\uD800-\uDBFF), the second from the low-surrogates range (\uDC00-\uDFFF).

  • The methods that only accept a char value cannot support supplementary characters. They treat char values from the surrogate ranges as undefined characters. For example, Character.isLetter(‘\uD840’) returns false , even though this specific value if followed by any low-surrogate value in a string would represent a letter.
  • The methods that accept an int value support all Unicode characters, including supplementary characters. For example, Character.isLetter(0x2F81A) returns true because the code point value represents a letter (a CJK ideograph).

In the Java SE API documentation, Unicode code point is used for character values in the range between U+0000 and U+10FFFF, and Unicode code unit is used for 16-bit char values that are code units of the UTF-16 encoding. For more information on Unicode terminology, refer to the Unicode Glossary.

This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.

Источник

Оцените статью