convert char to string in java
To convert a char
to a String
in Java, you can use the Character.toString(char)
method or concatenate the char
with an empty String
. Here's a step-by-step explanation:
- Using the
Character.toString(char)
method: - The
Character.toString(char)
method converts achar
to aString
. - To use this method, you need to pass the
char
value as an argument. - The method returns a
String
representation of thechar
value.
java
char c = 'a';
String str = Character.toString(c);
In this example, we have a char
variable c
with the value 'a'
. We then use the Character.toString()
method to convert c
to a String
and assign it to the variable str
.
- Concatenating the
char
with an emptyString
: - You can also convert a
char
to aString
by concatenating it with an emptyString
. - This works because when you concatenate a
char
with aString
, Java automatically converts thechar
to itsString
representation.
java
char c = 'a';
String str = "" + c;
In this example, we have a char
variable c
with the value 'a'
. By concatenating c
with an empty String
("" + c
), Java converts c
to a String
and assigns it to the variable str
.
Both approaches will give you the same result, which is a String
representation of the char
value.