Four methods for converting a character (Char) to a string in java

Source: Internet
Author: User
Tags anonymous


Method 1: Use Character. toString ()

The Character class provides a static method toString () to convert characters into strings.

Char ch = 'u ';
String charToString = Character. toString (ch );

 

Method 2: Use a string connector

When we use a string connector, other types of variables are automatically converted to the string type, as shown below:

Char ch = 'u ';
String str = "" + ch;

 
Method 3: use an anonymous array (anonymous array)

The anonymous array in java can be used to encapsulate a separate character to the character array, and then use this character array as the String constructor parameter.

Char ch = 'u ';
String fromChar = new String (new char [] {ch });

Method 4: Use String. valueOf ()

 

Char ch = 'u ';
String valueOfchar = String. valueOf (ch );

 
The complete sample code is as follows:


Public class CharToStringExample {
 
Public static void main (String args []) {
Char ch = 'u ';
 
// Char to string using Character class
String charToString = Character. toString (ch );
System. out. println ("Converting Char to String using Character class:" + charToString );
 
// Char to String using String concatenation
String str = "" + ch;
System. out. println ("Converting Char to String using String concatenation:" + str );
 
// Char to String using anonymous array
String fromChar = new String (new char [] {ch });
System. out. println ("Converting Char to String using anonymous array:" + fromChar );
 
// Char to String using String valueOf
String valueOfchar = String. valueOf (ch );
System. out. println ("Converting Char to String using String valueOf:" + valueOfchar );
 
}
 
}
 
Output:
Converting Char to String using Character class: U
Converting Char to String using String concatenation: U
Converting Char to String using anonymous array: U
Converting Char to String using String valueOf: U

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.