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:

  1. Using the Character.toString(char) method:
  2. The Character.toString(char) method converts a char to a String.
  3. To use this method, you need to pass the char value as an argument.
  4. The method returns a String representation of the char 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.

  1. Concatenating the char with an empty String:
  2. You can also convert a char to a String by concatenating it with an empty String.
  3. This works because when you concatenate a char with a String, Java automatically converts the char to its String 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.