[java] In Java how does one turn a String into a char or a char into a String?

Is there a way to turn a char into a String or a String with one letter into a char (like how you can turn an int into a double and a double into an int)? (please link to the relevant documentation if you can).

How do I go about finding something like this that I'm only vaguely aware of in the documentation?

This question is related to java string char

The answer is


As no one has mentioned, another way to create a String out of a single char:

String s = Character.toString('X');

Returns a String object representing the specified char. The result is a string of length 1 consisting solely of the specified char.


String someString = "" + c;
char c = someString.charAt(0);

I like to do something like this:

String oneLetter = "" + someChar;

String.valueOf('X') will create you a String "X"

"X".charAt(0) will give you the character 'X'


String g = "line";
//string to char
char c = g.charAt(0);
char[] c_arr = g.toCharArray();
//char to string
char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
//(or iterate the charArray and append each character to str -> str+=charArray[i])

//or String s= new String(chararray);


In order to convert string to char

 String str = "abcd";
char arr [] = new char[len]; // len is the length of the array
arr = str.toCharArray();

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to char

How can I convert a char to int in Java? C# - How to convert string to char? How to take character input in java Char Comparison in C Convert Char to String in C cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)' How to get the real and total length of char * (char array)? Why is conversion from string constant to 'char*' valid in C but invalid in C++ char *array and char array[] C++ - How to append a char to char*?