Algorithm


Algorithm to Convert Character to String:

  1. Start
  2. Declare a character variable (e.g., charValue) and assign the desired character.
  3. Create a string using the String.valueOf(charValue) method.
  4. The resulting string now contains the character representation.
  5. End

Algorithm to Convert String to Character:

  1. Start
  2. Declare a string variable (e.g., stringValue) and assign the desired string containing a single character.
  3. Use the charAt(0) method to extract the first character from the string.
  4. Assign the extracted character to a character variable (e.g., charValue).
  5. Now, charValue holds the character representation of the initial string.
  6. End

 

Code Examples

#1 Code Example- Convert char to String

Code - Java Programming

public class CharString {

    public static void main(String[] args) {
        char ch = 'c';
        String st = Character.toString(ch);
        // Alternatively
        // st = String.valueOf(ch);

        System.out.println("The string is: " + st);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
The string is: c

#2 Code Example- Convert char array to String

Code - Java Programming

public class CharString {

    public static void main(String[] args) {
        char[] ch = {'a', 'e', 'i', 'o', 'u'};

        String st = String.valueOf(ch);
        String st2 = new String(ch);

        System.out.println(st);
        System.out.println(st2);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
aeiou
aeiou

#3 Code Example- Convert String to char array

Code - Java Programming

import java.util.Arrays;

public class StringChar {

    public static void main(String[] args) {
        String st = "This is great";

        char[] chars = st.toCharArray();
        System.out.println(Arrays.toString(chars));
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
[T, h, i, s, , i, s, , g, r, e, a, t]
Advertisements

Demonstration


Java Programing Example to Convert Character to String and Vice-Versa-DevsEnv